C#操作XML文档使用XmlDocument类方法
2023-06-13 09:14:41 时间
W3C制定了XMLDOM标准。很多编程语言中多提供了支持W3CXMLDOM标准的API。我在之前的文章中介绍过如何使用Javascript对XML文档进行加载与查询。在本文中,我来介绍一下.Net中的XmlDocument类。它支持并扩展了W3CXMLDOM标准。它将整个XML文档都先装载进内存中,然后再对XML文档进行操作,所以如果XML文档内容过大,不建议使用XmlDocument类,因为会消耗过多内存。对于很大的XML文档,可以使用XmlReader类来读取。因为XmlReader使用Steam(流)来读取文件,所以不会对内存造成太大的消耗。下面就来看一下如何使用XmlDocument类。
(一)加载
加载XML比较常用的有三种方法:
publicvirtualvoidLoad(stringfilename);
publicvirtualvoidLoad(StreaminStream);
publicvirtualvoidLoadXml(stringxml);
下面代码演示如何使用它们:
复制代码代码如下:
(一)加载
加载XML比较常用的有三种方法:
publicvirtualvoidLoad(stringfilename);
publicvirtualvoidLoad(StreaminStream);
publicvirtualvoidLoadXml(stringxml);
下面代码演示如何使用它们:
XmlDocumentxmlDoc=newXmlDocument();
xmlDoc.Load("XMLFile1.xml");
EntityretrievedAnnotation=_orgService.Retrieve("annotation"
,newGuid("C1B13C7F-F430-E211-8FA1-984BE1731399"),newColumnSet(true));
byte[]fileContent=Convert.FromBase64String(retrievedAnnotation["documentbody"].ToString());
MemoryStreamms=newMemoryStream(fileContent);
XmlDocumentxmlDoc2=newXmlDocument();
xmlDoc2.Load(ms);
stringstr=@"<Customers><Customerid="01"city="Beijing"country="China"name="Lenovo"/></Customers>";
XmlDocumentxmlDoc3=newXmlDocument();
xmlDoc3.LoadXml(str);
(二)查询
对XML的元素、属性、文本的查询可以使用XPath。具体的定义可以参看w3school。
首先应该了解一下XPath表达式:
我们主要使用两个方法来查询XML文档,SelectNodes(xpathexpression)和SelectSingleNode(xpathexpression)。
SelectNodes返回一个XmlNodeList对象,也就是所有符合xpath表达式的xml节点都将会被返回,你需要对返回的结果进行遍历。
SelectSingleNode只返回第一个符合xpath表达式的节点,或者返回null。
以下面的XML文件为例,我们进行一些演示:
<?xmlversion="1.0"encoding="utf-8"?>
<Customers>
<Customerid="01"city="Beijing"country="China"name="Lenovo">
<Contactgender="female"title="Support">LiLi</Contact>
</Customer>
<Customerid="02"city="Amsterdam"country="TheNetherlands"name="Shell">
<Contactgender="male"title="SalesPerson">AaronBabbitt</Contact>
<Contactgender="female"title="SalesManager">DaisyCabell</Contact>
<Contactgender="male"title="SalesPerson">GabrielEads</Contact>
</Customer>
</Customers>
1.返回所有Contact节点:
XmlNodeListnodelist=xmlDoc.SelectNodes("/Customers/Customer/Contact");
foreach(XmlNodenodeinnodelist)
{
Console.WriteLine(node.OuterXml);
}
输出结果为:
<Contactgender="female"title="Support">LiLi</Contact>
<Contactgender="male"title="SalesPerson">AaronBabbitt</Contact>
<Contactgender="female"title="SalesManager">DaisyCabell</Contact>
<Contactgender="male"title="SalesPerson">GabrielEads</Contact>
2.返回id为02的customer:
XmlNodenode=xmlDoc.SelectSingleNode("/Customers/Customer[@id="02"]");
Console.WriteLine(node.OuterXml);
输出结果为:
<Customerid="02"city="Amsterdam"country="TheNetherlands"name="Shell">
<Contactgender="male"title="SalesPerson">AaronBabbitt</Contact>
<Contactgender="female"title="SalesManager">DaisyCabell</Contact>
<Contactgender="male"title="SalesPerson">GabrielEads</Contact>
</Customer>
3.返回含有contact名为LiLi的contact:
XmlNodenode=xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()="LiLi"]");
Console.WriteLine(node.OuterXml);
输出结果:
<Contactgender="female"title="Support">LiLi</Contact>
4.返回含有contact名为LiLi的customer。注意和3的区别:
XmlNodenode=xmlDoc.SelectSingleNode("/Customers/Customer[Contact/text()="LiLi"]");
Console.WriteLine(node.OuterXml);
输出结果:
<Customerid="01"city="Beijing"country="China"name="Lenovo">
<Contactgender="female"title="Support">LiLi</Contact>
</Customer>
5.(1)获取outerxml:
XmlNodenode=xmlDoc.SelectSingleNode("/Customers/Customer[@id="02"]");
Console.WriteLine(node.OuterXml);
(2)获取innerxml:
XmlNodenode=xmlDoc.SelectSingleNode("/Customers/Customer[@id="02"]");
Console.WriteLine(node.InnerXml);
(3)获取text
XmlNodenode=xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()="LiLi"]");
Console.WriteLine(node.InnerText);
(4)获取属性
XmlNodenode=xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()="LiLi"]");
Console.WriteLine(node.Attributes["gender"].Value);
(三)创建
以创建以下XML文档为例:
<?xmlversion="1.0"encoding="UTF-8"?>
<Customers>
<Customerid="01"name="Lenovo"country="China"city="Beijing">
<Contacttitle="Support"gender="female">LiLi</Contact>
</Customer>
</Customers>
varxmlDoc=newXmlDocument();
//Createthexmldeclarationfirst
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0","utf-8",null));
//Createtherootnodeandappendintodoc
varel=xmlDoc.CreateElement("Customers");
xmlDoc.AppendChild(el);
//CustomerLenovo
XmlElementelementCustomer=xmlDoc.CreateElement("Customer");
XmlAttributeattrID=xmlDoc.CreateAttribute("id");
attrID.Value="01";
elementCustomer.Attributes.Append(attrID);
XmlAttributecityID=xmlDoc.CreateAttribute("city");
cityID.Value="Beijing";
elementCustomer.Attributes.Append(cityID);
XmlAttributeattrCountry=xmlDoc.CreateAttribute("country");
attrCountry.Value="China";
elementCustomer.Attributes.Append(attrCountry);
XmlAttributenameCountry=xmlDoc.CreateAttribute("name");
nameCountry.Value="Lenovo";
elementCustomer.Attributes.Append(nameCountry);
el.AppendChild(elementCustomer);
//ContactLiLi
XmlElementelementContact=xmlDoc.CreateElement("Contact");
elementContact.InnerText="LiLi";
XmlAttributeattrGender=xmlDoc.CreateAttribute("gender");
attrGender.Value="female";
elementContact.Attributes.Append(attrGender);
XmlAttributetitleGender=xmlDoc.CreateAttribute("title");
titleGender.Value="Support";
elementContact.Attributes.Append(titleGender);
elementCustomer.AppendChild(elementContact);
xmlDoc.Save("test.xml");
总结:XmlDocument类是.NetAPI中提供的支持W3CXMLDOM标准的类。可以用它来创建和查询XML文档。由于XmlDocument要将XML文档的内容全部装载进内存中,所以对于读取内容过大的XML文档,不适合使用XmlDocument类,而可以使用XmlReader来完成读取。
相关文章
- c#数组赋初值_C#数组初始化
- c#windowsform应用_js调用webservice
- C# WPF:把文件给我拖进来!!!
- C# WPF DataGrid下面 使用CheckBox 选中事件
- C#通过log4net进行异常记录详解编程语言
- C#通过正则表达式抓取网页信息的类详解编程语言
- C#正则表达式使用介绍
- 访问修饰符(C#编程指南)
- c#组合模式
- C#调用和实现WebService,纯手工打造!
- 解决C#中WebBrowser的DocumentCompleted事件不执行的实现方法
- C#操作目录与文件的方法步骤
- C#Socket连接请求超时机制实现代码分享
- c#判断操作系统位数的示例分享
- c#中xml文档注释编译dll引用到其它项目示例
- C#中Params的用法
- C#在运行时动态创建类型的实现方法