XML Sample:
<?xml version= "1.0" encoding= "gb2312"?>
<bookstore>
<book genre= "Li 2 Red" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> waiting
<price>58.3</price </author> >
</book>
<book genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from Getting started to mastering </title>
<author> small six </author>
<price>58.3</price>
</book>
<book45 genre= " Li Zhanhong "isbn=" 2-3631-4 ">
<title>cs from Getting started to mastering </title>
<author> Rhubarb </author>
<price>58.3</price>
</book45>
</bookstore>
Test code:
<span style= "White-space:pre" > </span> xmldocument xmldoc = new XmlDocument ();
Xmldoc.load ("E:\\bookstore.xml"); Get all child nodes of the bookstore node//view this column more highlights: http://www.bianceng.cn/Programming/csharp/XmlNodeList nodelist = Xmldo C.selectsinglenode ("Bookstore").
ChildNodes; for (int i = 0; i < nodelist.count i++)//traverse each book node {//Convert child node type to XmlElement type Xmlele
ment XE = (XmlElement) nodelist.item (i); if (XE. Name = = "book" {//if the genre property value is "Li Zhanhong" if (XE). GetAttribute ("genre") = = "Li Zhanhong") {//continue to fetch all child nodes of XE child node XmlNodeList NLS = x
E.childnodes; for (int j = 0; J < NLS). Count; J + +) {XmlElement xe2 = (XmlElement) nls. Item (j);//conversion type//title, author, Price will be in Xe2.
In name, take the if (Xe2. Name = = "Author")//If {Xe2 is found.
innertext = "Karli Waston";//The modification} else//if not present new {Xe2.
SetAttribute ("Newattribute", "new Attribute");
}} else { If the value of the genre property is not "Li Zhanhong", it is modified to Li Zhanhong XE.
SetAttribute ("Genre", "Li Zhanhong"); If the book node does not exist, then a new one under that node {Xm
Lelement subelement = xmldoc.createelement ("Because this node is not book");
Subelement.innerxml = "BigDog"; Xe.
AppendChild (subelement); } xmldoc.save ("E:\\bookstore.xml"),//save.
Modified XML:
<?xml version= "1.0" encoding= "gb2312"?>
<bookstore>
<book genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> waiting
<price>58.3</price </author> >
</book>
<book genre= "Li Zhanhong" isbn= "2-3631-4" >
<title newattribute= "New properties" >cs from getting started to mastering </title>
<author>karli waston</author>
<price newattribute= "New Properties" >58.3</ price>
</book>
<book45 genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from entry to Mastery </ title>
<author> Rhubarb </author>
<price>58.3</price>
< Because this node is not book> bigdog</because this node is not book>
</book45>
</bookstore>
If you add a node under the root node now, the code is as follows:
XmlDocument xmldoc = new XmlDocument ();
Xmldoc.load ("E:\\bookstore.xml");
XmlNode root = xmldoc.documentelement;
XmlElement subelement = xmldoc.createelement ("New under Root node");
Subelement.innerxml = "BigDog";
Root. AppendChild (subelement);