本文介紹的是沒有指定命名空間的XML(如需要操作帶命名空間的,請點擊),最近公司項目做的都是基於xml處理的,網上也一大堆有關xml操作的文章,幾乎都是轉載來的。今天小弟特意自己寫3個例子,供需要的朋友學習。
xml文件
<?xml version="1.0" encoding="utf-8"?>
<Books>
<Book ID="1">
<Title>C#入門經典</Title>
<Price>95.00</Price>
</Book>
<Book ID="13">
<Title>C#從入門到精通</Title>
<Price>145.00</Price>
</Book>
<Book ID="4">
<Title>Java高級編程</Title>
<Price>165.00</Price>
</Book>
</Books>
//添加xml節點
private void addxml()
{
XmlDocument xmldoc = new XmlDocument();
//加載xml文件
xmldoc.Load(@"E:\Test\Test\tt.xml");
//查找 根節點 Books
XmlNode root = xmldoc.SelectSingleNode("Books");
//創建 子節點 Book
XmlElement book = xmldoc.CreateElement("Book");
book.SetAttribute("ID", "2");//設置子節點屬性
//創建 Book 子節點 Title
XmlElement title = xmldoc.CreateElement("Title");
title.InnerText = "C#高級編程";
//title 節點 添加到 root
book.AppendChild(title);
//創建 Book 子節點 Price
XmlElement price = xmldoc.CreateElement("Price");
price.InnerText = "145.00";
//price 節點 添加到 root
book.AppendChild(price);
//最后把book 節點添加到root
root.AppendChild(book);
//保存
xmldoc.Save(@"E:\Test\Test\tt.xml");
}
//刪除xml 節點
private void deletexml()
{
XmlDocument xmldoc = new XmlDocument();
//加載xml文件
xmldoc.Load(@"E:\Test\Test\tt.xml");
/*
//查找到ID=2的節點,刪除book 下面的子節點,最后會留下一個空的<book></book>
XmlNodeList nodelist = xmldoc.SelectNodes("//Books/Book[@ID=2]");//需了解xpath
foreach (XmlNode n in nodelist)
{
XmlElement xe = (XmlElement)n;
//刪除屬性
xe.RemoveAllAttributes();
//刪除節點
xe.RemoveAll();
}
*/
//刪除 book=2 節點(包括book 節點)
XmlNodeList nodelist = xmldoc.SelectNodes("//Books/Book[@ID=2]");//需了解xpath
foreach (XmlNode n in nodelist)
{
n.ParentNode.RemoveChild(n);
}
//保存
xmldoc.Save(@"E:\Test\Test\tt.xml");
}
//修改xml 節點
private void updatexml()
{
XmlDocument xmldoc = new XmlDocument();
//加載xml文件
xmldoc.Load(@"E:\Test\Test\tt.xml");
//查找到ID=2的節點,刪除book 下面的子節點,最后會留下一個空的<book></book>
XmlNodeList nodelist = xmldoc.SelectNodes("//Books/Book[@ID=3]");//需了解xpath
foreach (XmlNode n in nodelist)
{
XmlElement xe = (XmlElement)n;//XmlElement繼承XmlNode
//將屬性 修改為13
xe.SetAttribute("ID","13");
//查找title節點
XmlNode nn = n.SelectSingleNode("Title");
nn.InnerText = "C#從入門到精通";
}
//保存
xmldoc.Save(@"E:\Test\Test\tt.xml");
}
操作節點還有CDATA
需要操作的XML文件:
<Info>
<Link><![CDATA[<a href="http://www.52taiqiu.com">52台球網</a>]]></Link>
</Info>
修改Link中的值
XmlDocument xmldoc = new XmlDocument();
//加載xml文件
xmldoc.Load(@"E:\Test\Test\測試.xml");
XmlNode nameNode = xmldoc.SelectSingleNode("/Info/Link");
nameNode.InnerText = "";//如果是修改,需要把原先的值清空。
nameNode.AppendChild(xmldoc.CreateCDataSection("<a href=\"http://www.52taiqiu.com\">52台球網</a>"));
xmldoc.Save(@"E:\Test\Test\測試.xml");