XmlDocument和LINQ to XML两种方式对xml的创建、查询

假设一个xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<Persons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.xxx.com/XxxSystem">
  <Person id="1">
    <Name>张三</Name>
    <Age>18</Age>
  </Person>
  <Person id="2">
    <Name>李四</Name>
    <Age>20</Age>
  </Person>
</Persons>

1)XmlDocument方式

创建xml代码如下:

 private void button1_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(dec);
            //根节点
            XmlElement root = doc.CreateElement("Persons");
            doc.AppendChild(root);
            root.AddEleAttr(doc, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            root.AddEleAttr(doc, "xmlns", "http://www.xxx.com/XxxSystem");
            //根节点的每个独立子节点
            XmlElement body = doc.CreateElement("Person");
            body.AddEleAttr(doc, "id", "1");   
            body.AddChildNode(doc, "Name", "张三");
            body.AddChildNode(doc, "Age", "18");    
            root.AppendChild(body);

            //根节点的每个独立子节点
            body = doc.CreateElement("Person");
            body.AddEleAttr(doc, "id", "2");
            body.AddChildNode(doc, "Name", "李四");
            body.AddChildNode(doc, "Age", "20");           
            root.AppendChild(body);

            doc.Save("person.xml");
        }
查询id=2时的姓名和年龄:
 private void button2_Click(object sender, EventArgs e)
        {
             XmlDocument doc = new XmlDocument();
             using (StreamReader sr = new StreamReader("person.xml", Encoding.UTF8))
             {
                 doc.Load(sr);
                 XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
                 nsMgr.AddNamespace("ns", "http://www.xxx.com/XxxSystem");
                 XmlNodeList nodes = doc.SelectNodes("//ns:Person[@id=2]", nsMgr);
                 foreach (XmlNode item in nodes)
                 {
                     string name = item.SelectSingleNode("//ns:Name", nsMgr).InnerText;
                     string age = item.SelectSingleNode("//ns:Age", nsMgr).InnerText;
                     MessageBox.Show(string.Format("{0}:{1}", name, age));
                 }
             }
        }      
备注:上面创建xml用到的两个扩展方法如下:

        /// <summary>
        /// XML元素添加属性
        /// </summary>
        public static void AddEleAttr(this XmlElement src, XmlDocument doc, string name, string value)
        {
            XmlAttribute attr = doc.CreateAttribute(name);
            attr.Value = value;
            src.Attributes.Append(attr);
        }
        /// <summary>
        /// XML元素添加子节点
        /// </summary>
        public static void AddChildNode(this XmlElement src, XmlDocument doc, string name, string innerText)
        {
            XmlElement elem = doc.CreateElement(name);
            elem.InnerText = innerText;
            src.AppendChild(elem);
        }

2)LINQ to XML方式

创建xml代码如下:

   //using System.Xml.Linq;     
        private void button1_Click(object sender, EventArgs e)
        {
            XNamespace ns = "http://www.xxx.com/XxxSystem";
            XDocument doc = new XDocument(
                new XDeclaration("1.0","UTF-8",null),
                new XElement(ns + "Persons",
                    new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),                          
                    new XElement("Person",
                        new XAttribute("id","1"),
                        new XElement("Name","张三"),
                        new XElement("Age",18)
                    ),
                    new XElement("Person",
                        new XAttribute("id", "2"),
                        new XElement("Name", "李四"),
                        new XElement("Age", 20)
                    )
                )
             );
            doc.Save("person.xml");
        }
查询id=2时的姓名和年龄:
 private void button2_Click(object sender, EventArgs e)
        {
            using (StreamReader sr = new StreamReader("person.xml", Encoding.UTF8))
            {
                XDocument doc = XDocument.Load(sr);
                XNamespace ns = "http://www.xxx.com/XxxSystem";
                var qry = doc.Descendants(ns + "Persons")
                    .Elements(ns + "Person")
                    .Where(p => p.Attribute("id").Value == "2")
                    .Select(p => new
                    {
                        Name = p.Element(ns + "Name").Value,
                        Age = p.Element(ns + "Age").Value
                    });
                foreach(var p in qry)
                    MessageBox.Show(string.Format("{0}:{1}", p.Name, p.Age));               
            }
        }



你可能感兴趣的:(XmlDocument和LINQ to XML两种方式对xml的创建、查询)