标签:
需要引用的命名空间: using System.Xml;
常用的类:XmlDocument、XmlElement、XmlNode、XmlNodeList
一、使用XmlDocument创建xml
//创建XmlDocument对象 XmlDocument xmlDoc = new XmlDocument(); //建立Xml的定义声明 XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "GB2312", null); xmlDoc.AppendChild(dec); //创建根节点 XmlElement root = xmlDoc.CreateElement("Books"); xmlDoc.AppendChild(root); XmlNode book = xmlDoc.CreateElement("Book"); XmlElement title = xmlDoc.CreateElement("Title"); title.InnerText = "SQL Server"; book.AppendChild(title); XmlElement isbn = xmlDoc.CreateElement("ISBN"); isbn.InnerText = "444444"; book.AppendChild(isbn); XmlElement author = xmlDoc.CreateElement("Author"); author.InnerText = "jia"; book.AppendChild(author); XmlElement price = xmlDoc.CreateElement("Price"); price.InnerText = "120"; price.SetAttribute("Unit", "_fad"); book.AppendChild(price); XmlNode book2 = xmlDoc.CreateElement("Book"); XmlElement title2 = xmlDoc.CreateElement("Title"); title2.InnerText = "C#高级编程"; book2.AppendChild(title2); XmlElement isbn2 = xmlDoc.CreateElement("ISBN"); isbn2.InnerText = "88888"; book2.AppendChild(isbn2); XmlElement author2 = xmlDoc.CreateElement("Author"); author2.InnerText = "Longsi"; book2.AppendChild(author2); XmlElement price2 = xmlDoc.CreateElement("Price"); price2.InnerText = "1200"; price2.SetAttribute("Unit", "abc"); book2.AppendChild(price2); XmlElement title3 = xmlDoc.CreateElement("Title"); title3.InnerText = "我是最外面的Title"; title3.SetAttribute("name", "lxf"); root.AppendChild(book); root.AppendChild(book2); root.AppendChild(title3); xmlDoc.Save(@"F:\Books.xml"); Console.WriteLine("xml文档创建成功");
结果:
<?xml version="1.0" encoding="GB2312"?>
<Books>
<Book>
<Title>SQL Server</Title>
<ISBN>444444</ISBN>
<Author>jia</Author>
<Price Unit="_fad">120</Price>
</Book>
<Book>
<Title>C#高级编程</Title>
<ISBN>88888</ISBN>
<Author>Longsi</Author>
<Price Unit="abc">1200</Price>
</Book>
<Title name="lxf">我是最外面的Title</Title>
</Books>
二、使用XmlDocument 查询xml
主要方法SelectNodes(xPath字符串)
//查询所有Title节点
XmlNodeList aa = xmlDoc.SelectNodes("//Title");
查询具有name属性的Title节点
XmlNodeList aa = xmlDoc.SelectNodes("//Title[@name]");
foreach (XmlNode item in aa)
{
Console.WriteLine(item.InnerText);
}
总结:传统的XmlDocument在创建xml上没有使用Ling to Xml简介
但在查询操作上,结合使用xPath,还是很容易很强大的。
xPath用法详见 http://www.cnblogs.com/lxf1117/p/3936239.html
标签:
原文地址:http://www.cnblogs.com/lxf1117/p/4178678.html