C#用XmlDocument操作XML
1.加載xml文件
?? string xmlPath = AppDomain.CurrentDomain.BaseDirectory+"xml/test.xml";
?? XmlDocument xmlDoc = new XmlDocument();
?? xmlDoc.Load(xmlPath);//這里是xml文件的路徑
?? string xmlString="<books><book>test</book></books>";
?? xmlDoc.LoadXml(xmlString);//這里是加載一段XML字符串并將它轉換為xml
2、用xpath來查詢節點
??? XmlNodeList nodeList = xmlDoc.SelectNodes("/bookstore/book/title");//查詢節點集
??? XmlNodeList node = xmlDoc.SelectSingleNode("/bookstore/book/title[@speciality='computer']");//根據屬性查詢單個節點
3、遍歷節點集
??? foreach (XmlNode node in nodeList)
4、給某個節點添加新的屬性
??? XmlAttribute attr = xmlDoc.CreateAttribute("specialty");
??? attr.Value = "computer";
??? node.Attributes.Append(attr);
5、刪除某個節點的某個屬性,當然也可以根據屬性的下標來刪除(這里就不舉例了)
??? ?XmlNode node = xmlDoc.SelectSingleNode("/bookstore/book[@ISBN='1-861003-11-0']/title");
??????????? XmlAttribute attr = node.Attributes["specialty"];
??????????? if (attr.Value == "computer1")
??????????? {
??????????????? node.Attributes.Remove(attr);
??????????? }
6、修改某個節點的value值,但節點的tag名稱是不能修改的,只能先刪除再添加
????? node.Attributes["specialty"].Value="xiaochun";
7、添加節點
??? XmlElement element = xmlDoc.CreateElement("book");
??????????? element.InnerXml = "<test>create element</test>";
??????????? XmlNode node = xmlDoc.SelectSingleNode("/bookstore");
??????????? node.AppendChild(element);
8、修改節點就是先查詢到某個節點,然后再將他的屬性再設置一次就行了(這里就不舉例了)
9、刪除節點
???? XmlNodeList nodeList = xmlDoc.SelectNodes("/bookstore/book");
??????????? foreach (XmlNode node in nodeList)
??????????? {
??????????????? if (node.Attributes.Count == 0)//這里表示沒有屬性的節點
??????????????? {
??????????????????? xmlDoc.SelectSingleNode("/bookstore").RemoveChild(node);
??????????????? }
??????????? }
10、保存xml文檔
???? xmlDoc.Save(xmlPath);
11、創建一個完整的XML文檔
????? XmlDocument xmlDoc = new XmlDocument();
??????????? XmlDeclaration declare = xmlDoc.CreateXmlDeclaration("1.0","gb2312",null);
??????????? xmlDoc.AppendChild(declare);
??????????? XmlElement root = xmlDoc.CreateElement("books");
??????????? xmlDoc.AppendChild(root);
??????????? XmlElement bookElement = xmlDoc.CreateElement("book");
??????????? bookElement.InnerXml = "<name>javascript</name>";
??????????? xmlDoc.SelectSingleNode("/books").AppendChild(bookElement);
??????????? XmlElement bookElement2 = xmlDoc.CreateElement("book");
??????????? bookElement.InnerXml = "<name>xml</name>";
??????????? XmlAttribute attr = xmlDoc.CreateAttribute("title");
??????????? attr.Value = "test";
??????????? bookElement2.Attributes.Append(attr);
??????????? xmlDoc.SelectSingleNode("/books").AppendChild(bookElement2);
??????????? xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory+"/xml/test2.xml");
轉載于:https://www.cnblogs.com/msql/archive/2012/11/30/2796235.html
總結
以上是生活随笔為你收集整理的C#用XmlDocument操作XML的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “半空直下视”下一句是什么
- 下一篇: 钢材一吨多少钱啊?