518
windows
C# 關於XML遍曆新增節點,修改屬性小例
XML樣例:
<?xml version="1.0" encoding="gb2312"?> <bookstore> <book genre="李2紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </book> <book genre="李讚紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>小六</author> <price>58.3</price> </book> <book45 genre="李讚紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>大黃</author> <price>58.3</price> </book45> </bookstore>
測試代碼:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("E:\\bookstore.xml");
//獲取bookstore節點的所有子節點
XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes;
for (int i = 0; i < nodeList.Count; i++)//遍曆每個book節點
{ //將子節點類型轉換為XmlElement類型
XmlElement xe = (XmlElement)nodeList.Item(i);
if (xe.Name == "book")
{ //如果genre屬性值為“李讚紅”
if (xe.GetAttribute("genre") == "李讚紅")
{ //繼續獲取xe子節點的所有子節點
XmlNodeList nls = xe.ChildNodes;
for (int j = 0; j < nls.Count; j++)
{
XmlElement xe2 = (XmlElement)nls.Item(j);//轉換類型
//title、author、price都會在xe2.Name中取到
if (xe2.Name == "author")//如果找到
{
xe2.InnerText = "Karli Waston";//則修改
}
else //如果不存在則新建
{
xe2.SetAttribute("NewAttribute", "新增屬性");
}
}
}
else
{
//如果genre屬性值不為“李讚紅”,則修改為李讚紅
xe.SetAttribute("genre", "李讚紅");
}
}
else //如果不存在book節點,則在該節點下新增一個book下級節點
{
XmlElement subElement = xmlDoc.CreateElement("因為這個節點不是book");
subElement.InnerXml = "BigDog";
xe.AppendChild(subElement);
}
}
xmlDoc.Save("E:\\bookstore.xml");//保存。
修改後的XML:
<?xml version="1.0" encoding="gb2312"?> <bookstore> <book genre="李讚紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>候捷</author> <price>58.3</price> </book> <book genre="李讚紅" ISBN="2-3631-4"> <title NewAttribute="新增屬性">CS從入門到精通</title> <author>Karli Waston</author> <price NewAttribute="新增屬性">58.3</price> </book> <book45 genre="李讚紅" ISBN="2-3631-4"> <title>CS從入門到精通</title> <author>大黃</author> <price>58.3</price> <因為這個節點不是book>BigDog</因為這個節點不是book> </book45> </bookstore>如果現在根節點下新增某個節點,代碼如下:
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("E:\\bookstore.xml"); XmlNode root = xmlDoc.DocumentElement; XmlElement subElement = xmlDoc.CreateElement("根節點下新增"); subElement.InnerXml = "BigDog"; root.AppendChild(subElement);
最後更新:2017-04-03 12:54:23