C#解析XML

2016-11-21 19:02:42来源:CSDN作者:qq_18995513人点击

最近在尝试用WPF搞点桌面小应用。

C#中使用System.Xml.XmlDocument类对XML文件进行操作。

文档详情如下:
https://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx

除了文档给出的例子,还搜到了更直观的例子:

解析文件内容:

<?xml version="1.0" encoding="utf-8" ?><users>  <user id="1001">    <name>张三</name>    <email>123456789@136.com</email>    <phone>13400000000</phone>  </user>  <user id="1002">    <name>李四</name>    <email>123456789@126.com</email>    <phone>15800000000</phone>  </user></users>

解析代码:

public static void ReadParseXml(){    XmlDocument xmlDoc = new XmlDocument();    xmlDoc.Load("E:/Data/VisualStudio/C#/app001/ConsoleApp/App01/userlist.xml");    //查找<users>    XmlNode root = xmlDoc.SelectSingleNode("users");    //获取到所有<users>的子节点    XmlNodeList nodeList =root.ChildNodes;    //遍历所有子节点    foreach (XmlNode xn in nodeList)    {        XmlElement xe = (XmlElement)xn;        XmlNodeList subList = xe.ChildNodes;        foreach (XmlNode xmlNode in subList)        {            if ("name".Equals(xmlNode.Name))            {                Console.WriteLine("姓名:" + xmlNode.InnerText);            }            else if ("email".Equals(xmlNode.Name))            {                Console.WriteLine("邮箱:" + xmlNode.InnerText);            }                          }                }}public static void ReadParseXml2(){    XmlDocument xmlDoc = new XmlDocument();    xmlDoc.Load("E:/Data/VisualStudio/C#/app001/ConsoleApp/App01/userlist.xml");    //查找<users>    XmlNode root = xmlDoc.SelectSingleNode("users");    //获取到所有<users>的子节点    XmlNodeList nodeList = xmlDoc.SelectSingleNode("users").ChildNodes;    //遍历所有子节点    foreach (XmlNode xn in nodeList)    {        XmlElement xe = (XmlElement)xn;        Console.WriteLine("节点的ID为: " + xe.GetAttribute("id"));        XmlNodeList subList = xe.ChildNodes;        foreach (XmlNode xmlNode in subList)        {            Console.WriteLine(xmlNode.InnerText);        }    }}

以上例子来自:

http://blog.163.com/nice_2011/blog/static/18900817020131260438396/

其他参考信息:

http://www.cnblogs.com/a1656344531/archive/2012/11/28/2792863.html
http://blog.csdn.net/tiemufeng1122/article/details/6723764/

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台