c#操作主要使用如下相关类
XmlDocument:msdn上的说表示一个xml文件,就是通过load方法加载后,XmlDocument就代表整个xml文件内容
XmlNode:表示单个节点信息
XmlNodeList:msdn上说的是表示排序的节点集合,可通过其他对象的SelectNodes,SelectSingleNode方法和ChildNodes属性获取到
示例xml文件:
<?xml version="1.0" encoding="utf-8" ?> <TestXml> <firstNode> <id>第一个id</id> <secondNode> second1 </secondNode> </firstNode> <firstNode> <id>第二个id</id> <secondNode> second2 </secondNode> </firstNode> </TestXml>
1、加载xml文档到XmlDocument对象中
1 public void LoadXml() 2 { 3 XmlDocument xmlDoc=new XmlDocument(); 4 string pathString="";//文件实际存放的路径 5 xmlDoc.Load(pathString); 6 }
2、查找节点相关操作
(1)查找节点集合
根据节点名称查询
public static void SelectXmlNodeList() { XmlDocument xmlDoc=new XmlDocument(); string pathString="";//文件实际存放的路径 xmlDoc.Load(pathString); XmlNodeList FirstNodeList=xmlDoc.SelectNodes("TestXml"); }操作结果为TestXml节点中的子节点集合,其内容遍历输出为:
<firstNode><id>第一个id</id><secondNode> second1 </secondNode></firstNode><firstNode><id>第二个id</id><secondNode> second2 </secondNode></firstNode>
根据节点路径查询
public static void SelectXmlNodeList() { XmlDocument xmlDoc=new XmlDocument(); string pathString="";//文件实际存放的路径 xmlDoc.Load(pathString); XmlNodeList NodeList=xmlDoc.SelectNodes("TestXml/firstNode"); foreach(XmlNode xmlNode in NodeList) Console.WriteLine(xmlNode.InnerXml); }public static void SelectXmlNodeList() { XmlDocument xmlDoc=new XmlDocument(); string pathString="";//文件实际存放的路径 xmlDoc.Load(pathString); XmlNodeList NodeList=xmlDoc.SelectNodes("TestXml/firstNode"); foreach(XmlNode xmlNode in NodeList) Console.WriteLine(xmlNode.InnerXml); }
public static void SelectXmlNodeList() { XmlDocument xmlDoc=new XmlDocument(); string pathString="";//文件实际存放的路径 xmlDoc.Load(pathString); XmlNodeList NodeList=xmlDoc.SelectNodes("TestXml/firstNode"); foreach(XmlNode xmlNode in NodeList) Console.WriteLine(xmlNode.InnerXml); } BlogInsertHtml
输出结果为
<id>第一个id</id> <secondNode> second1 </secondNode> <id>第二个id</id> <secondNode> second2 </secondNode>如果把Console.WriteLine(xmlNode.OuterXml);输出结果如下:
<firstNode> <id>第一个id</id> <secondNode> second1 </secondNode> </firstNode> <firstNode> <id>第二个id</id> <secondNode> second2 </secondNode> </firstNode>
转载于:https://www.cnblogs.com/wzy0216/archive/2012/12/29/2838591.html
相关资源:C#读取XML配置文件