c#

位置:IT落伍者 >> c# >> 浏览文章

C#高级编程:使用XmlDocument对象[2]


发布日期:2024年02月22日
 
C#高级编程:使用XmlDocument对象[2]
——此文章摘自《C#高级编程(第版)》定价元 特价元 购买

private void button_Click(object sender SystemEventArgs e)

{

//change path to match your structure

docLoad(\\\\\\booksxml);

//create a new book element

XmlElement newBook=docCreateElement(book);

//set some attributes

newBookSetAttribute(genreMystery);

newBookSetAttribute(publicationdate);

newBookSetAttribute(ISBN);

//create a new title element

XmlElement newTitle=docCreateElement(title);

newTitleInnerText=The Case of the Missing Cookie;

newBookAppendChild(newTitle);

//create new author element

XmlElement newAuthor=docCreateElement(author);

newBookAppendChild(newAuthor);

//create new name element

XmlElement newFTEL=docCreateElement(name);

newNameInnerText=C Monster;

newAuthorAppendChild(newName);

//create new price element

XmlElement newPrice=docCreateElement(price);

newPriceInnerText=;

newBookAppendChild(newPrice);

//add to the current document

docDocumentElementAppendChild(newBook);

//write out the doc to disk

XmlTextWriter tr=new XmlTextWriter(\\\\\\booksEditxmlnull);

trFormatting=FormattingIndented;

docWriteContentTo(tr);

trClose();

//load listBox with all of the titles including new one

XmlNodeList nodeLst=docGetElementsByTagName(title);

foreach(XmlNode node in nodeLst)

listBoxItemsAdd(nodeInnerText);

}

在执行这段代码后会得到与上一个示例相同的结果但本例在列表框中添加了一本书The Case of the Missing Cookie单击cookie caper标题会显示与其他标题一样的信息中断代码可以看出这是一个相当简单的过程首先创建一个新的book元素

XmlElement newBook = docCreateElement(book);

CreateElement()有个重载方法可以指定

●元素名

●名称和命名空间URI

●前缀本地名和命名空间

创建了该元素后就要添加属性了

newBookSetAttribute(genreMystery);

newBookSetAttribute(publicationdate);

newBookSetAttribute(ISBN);

创建了属性后就要添加书籍的其他元素了

XmlElement newTitle = docCreateElement(title);

newTitleInnerText = The Case of the Missing Cookie;

newBookAppendChild(newTitle);

再次创建一个新的基于XmlElement的对象(newTitle)把InnerText属性设置为新书名把该元素添加为book元素的一个子元素对book元素中的其他元素重复这一操作注意把name元素添加为author元素的一个子元素这样就可以在其他book元素中得到合适的嵌套关系

[] [] []

               

上一篇:C#高级编程:使用XmlDocument对象[1]

下一篇:C#高级编程:使用XmlDocument对象[3]