Linq学习随笔二------LINQ to XML

LINQ to XML

LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. LINQ to XML uses the latest .NET Framework language capabilities and is comparable to an updated, redesigned Document Object Model (DOM) XML programming interface.

Linq to XML是一种新的XML编程方法,可以让XML代码更简洁,并且功能更强大。

以下示例代码中会用到的xmlTemplate.xml

<?xml version="1.0"?>  
<SanGuo ChaoDai="HanChao">
  <Shu Wang="LiuBei">
    <WuJiangs>
      <WuJiang XingBie="0" WuQi="QingLongYanYueDao">GuanYu</WuJiang>
      <WuJiang XingBie="0" WuQi="BaZhangSheMao">ZhangFei</WuJiang>
      <WuJiang XingBie="1" WuQi="Jian">SunShangXiang</WuJiang>
    </WuJiangs>
    <ChengChi>
      <ChengDu></ChengDu>
      <GuangDu></GuangDu>
      <XinDu></XinDu>
    </ChengChi>
  </Shu>
  <Wei Wang="SunQuan">
    <WuJiangs>
      <WuJiang XingBie="0" WuQi="Jian">ZhouYu</WuJiang>
    </WuJiangs>
    <ChengChi>
      <SuZhou></SuZhou>
      <HuZhou></HuZhou>
      <YangZhou></YangZhou>
    </ChengChi>
  </Wei>
  <Wu Wang="LiuBei">
    <WuJiangs>
      <WuJiang XingBie="0" WuQi="DaDao">XuChu</WuJiang>
      <WuJiang XingBie="0" WuQi="ShuangJi">DianWei</WuJiang>
    </WuJiangs>
    <ChengChi>
      <DuYi></DuYi>
      <DaLiang></DaLiang>
    </ChengChi>
  </Wu>
</SanGuo>
View Code

 

1.创建XML树

构造方法XElement,这个类构造出来的相当于Xml里的node节点,XAttribute类对应XML node中的attribute,具体使用方法可以参看下面的示例代码

 1             XElement sanGuoXml = 
 2                 new XElement("SanGuo", 
 3                     new XAttribute("ChaoDai", "HanChao"),
 4                     new XElement("Shu", 
 5                         new XAttribute("Wang", "LiuBei"),
 6                         new XElement("WuJiang", 
 7                             new XElement("GuanYu", 
 8                                 new XAttribute("XingBie", "0"),
 9                                 new XAttribute("WuQi", "QingLongYanYueDao")),
10                             new XElement("ZhangFei",
11                                 new XAttribute("XingBie", "0"),
12                                 new XAttribute("WuQi", "BaZhangSheMao")),                            
13                             new XElement("SunShangXiang",
14                                 new XAttribute("XingBie", "1"),
15                                 new XAttribute("WuQi", "Jian"))
16                             )
17                         ),
18                     new XElement("Wei",
19                         new XAttribute("Wang", "SunQuan"),
20                         new XElement("WuJiang", 
21                             new XElement("ZhouYu", 
22                                 new XAttribute("XingBie", "0"),
23                                 new XAttribute("WuQi", "Jian"))
24                             )
25                         ),
26                     new XElement("Wu",
27                         new XAttribute("Wang", "LiuBei"),
28                         new XElement("WuJiang", 
29                             new XElement("XuChu", 
30                                 new XAttribute("XingBie", "0"),
31                                 new XAttribute("WuQi", "DaDao")),
32                             new XElement("DianWei",
33                                 new XAttribute("XingBie", "0"),
34                                 new XAttribute("WuQi", "ShuangJi"))
35                             )
36                         )
37                     );

输出结果

<SanGuo ChaoDai="HanChao">
  <Shu Wang="LiuBei">
    <WuJiang>
      <GuanYu XingBie="0" WuQi="QingLongYanYueDao" />
      <ZhangFei XingBie="0" WuQi="QingLongYanYueDao" />
      <SunShangXiang XingBie="1" WuQi="Jian" />
    </WuJiang>
  </Shu>
  <Wei Wang="SunQuan">
    <WuJiang>
      <ZhouYu XingBie="0" WuQi="Jian" />
    </WuJiang>
  </Wei>
  <Wu Wang="LiuBei">
    <WuJiang>
      <XuChu XingBie="0" WuQi="DaDao" />
      <DianWei XingBie="0" WuQi="ShuangJi" />
    </WuJiang>
  </Wu>
</SanGuo>

2.Clone vs Attach

在将 XNode(包括 XElement)或 XAttribute 对象添加到新Tree时,如果新内容没有父节点,则对象会被attach到 XML 树。 如果新内容已经有父节点,并且是另一 XML 树的一部分,则Clone新内容。 然后将新clone的内容附加到 XML 树中,示例代码如下。

 1             XElement xmlTree1 = new XElement("Root",
 2                 new XElement("Child1", 1)
 3             );
 4             XElement child2 = new XElement("Child2", 2);// Create an element that is not parented. 
 5             XElement xmlTree2 = new XElement("Root",
 6                 xmlTree1.Element("Child1"),
 7                 child2
 8             );
 9  
10             Console.WriteLine("Child1 was {0}", //output Child1 was cloned
11                 xmlTree1.Element("Child1") == xmlTree2.Element("Child1") ?
12                 "attached" : "cloned");  
13             Console.WriteLine("Child2 was {0}", //output Child2 was attached
14                 child2 == xmlTree2.Element("Child2") ?
15                 "attached" : "cloned");

3.通过读取字符串或者File加载XML

1             XElement readyMadeXml1 = XElement.Parse(File.ReadAllText(@"..\..\xmlTemplate.xml"));
2             XElement readyMadeXml2 = XElement.Load(@"..\..\xmlTemplate.xml");
3             XDocument readyMadeXml3 = XDocument.Parse(File.ReadAllText(@"..\..\xmlTemplate.xml"), LoadOptions.PreserveWhitespace);
4             XDocument readyMadeXml4 = XDocument.Load(@"..\..\xmlTemplate.xml", LoadOptions.PreserveWhitespace);

上面的code中会看到一个新的类XDocument ,它的作用类似于XMLDocument,3,4行中会发现第二个参数为LoadOptions,其作用是保留xml一些特定的内容,例如默认情况下在load或者parse后,xml中无意义的空格会被删除,如果想保留的话就需要在方法中传入参数LoadOptions.PreserveWhitespace。

4.使用XML命名空间

Linq中与xml的namespace对于的类是XNamespace ,具体的使用方法比传统的方式更简洁,示例代码如下

 1             // The http://www.adventure-works.com namespace is forced to be the default namespace.  
 2             XNamespace aw = "http://www.adventure-works.com";
 3             XNamespace fc = "www.fourthcoffee.com";
 4             XElement root = new XElement(aw + "Root",
 5                 new XAttribute("xmlns", "http://www.adventure-works.com"),
 6                 new XAttribute(XNamespace.Xmlns + "coffee", "www.fourthcoffee.com"),
 7                 new XElement(fc + "Child",
 8                     new XElement(aw + "DifferentChild", "other content"),
 9                     new XElement(aw + "DifferentChild", "hehe")
10                 ),
11                 new XElement(aw + "Child2", "c2 content"),
12                 new XElement(fc + "Child3", "c3 content")
13             );

aw为默认命名空间,没有前缀,fc有前缀,构造出来的xml如下

<Root xmlns="http://www.adventure-works.com" xmlns:coffee="www.fourthcoffee.com">
  <coffee:Child>
    <DifferentChild>other content</DifferentChild>
    <DifferentChild>hehe</DifferentChild>
  </coffee:Child>
  <Child2>c2 content</Child2>
  <coffee:Child3>c3 content</coffee:Child3>
</Root>
View Code

因为xml中包含命名空间,所以对应的在查询xml的节点时,需要在查询时在XName中使用+包含XNamespace信息,示例代码如下

1             IEnumerable<XElement> reslut = from e in root.Elements(fc + "Child").Elements(aw + "DifferentChild")
2                                       select e;
3             foreach (XElement e in reslut)
4             {
5                 Console.WriteLine(e.Value);
6             }

即使默认命名空间不会有前缀,但是在查询的时候也要需要在节点名前面加默认XNamespace +。

5.检索查询修改XML

这部分不给出具体的说明和示例代码,说多了看过就忘了,自己写代码过程中,实际动手最实际,不管是Linq to Object还是Linq to xml,都属于Linq,所以上篇Linq to Object提到的对于Linq的用法,在Linq to Xml里也同样适用。感兴趣的可以看下下面的链接

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml-axes

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/querying-xml-trees

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/advanced-query-techniques-linq-to-xml

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/modifying-xml-trees-linq-to-xml

这里特别提一下XPath,XPath在Linq to xml中也同样的功能,该功能是通过 System.Xml.XPath.Extensions 中的扩展方法实现的,在使用相关方法时需要引用System.Xml.XPath。

5.XML开发中的内存和性能问题

在处理XML的时候需要特别注意内存的使用情况,如果盲目的将这个xml都加载了,如果XML比较小还看不出来影响,如果是有上百万node的xml的时候内存问题就很严重了,那如何控制内存呢,其实很简单,只把你需要的分析的node使用XElement构造出来,尽可能减少构造XElement的数量,使用流的方式将xml分片段进行处理,下例使用XmlReader流对xml进行分段处理

 1         static void Main(string[] args)
 2         {
 3             IEnumerable<string> wuJiangChild = from w in StreamRootChildDoc(new StringReader(File.ReadAllText(@"..\..\xmlTemplate.xml")))
 4                                                where (int)w.Attribute("XingBie") == 0
 5                                                select w.Value;
 6         }
 7 
 8         static IEnumerable<XElement> StreamRootChildDoc(StringReader stringReader)
 9         {
10             using (XmlReader reader = XmlReader.Create(stringReader))
11             {
12                 reader.MoveToContent();
13                 // Parse the file and display each of the nodes.  
14                 while (reader.Read())
15                 {
16                     switch (reader.NodeType)
17                     {
18                         case XmlNodeType.Element:
19                             if (reader.Name == "WuJiang")
20                             {
21                                 XElement el = XElement.ReadFrom(reader) as XElement;
22                                 if (el != null)
23                                     yield return el;
24                             }
25                             break;
26                     }
27                 }
28             }
29         }

方法StreamRootChildDoc的作用就是从XML中过滤出来需要分析的node,之后构造成XElement集合返回,方法中有一个不常用的关键字yield,该关键字会向编译器指出该关键字所在的方法是迭代器块,yield需要分别结合return或者break使用,这里使用的yield return最大的特点是将XElement“按需生产”出来,而不是一次性都“批量生产”出来供人使用,这么说可能大家想不明白,对照上面的code看下,在执行第3行的时候,会调用方法StreamRootChildDoc,但是该方法不是一次性执行完的,方法内执行到23行时,会返回一个XElement,而不是XElement集合,接着会继续执行第4行,如果满足条件执行第5行,接下来执行的是第14行,如此往复,直到循环完。如果按照传统的方式,我们可能会在方法StreamRootChildDoc的第一行中定义一个空的集合,之后再23行中把满足条件的XElement加入到集合中,最后再将集合return,这种方式就是前面提到的“批量生产”。大家可以很简单的看出来“按需生产”对内存的负担更小,所以这种方式对于解析大XML的时候能一定程度上的控制内存使用量。

除了上面的内存问题,对于XName的使用也会影响到xml操作的性能,但是不很大,使用XName的时候尽量使用显示的方式,减少使用隐式的转换(第一点下的示例代码中不管是new XElement,还是new XAttribute,采用的都是将字符串隐式的转换为XName),特别是同样的XName被反复使用的情况下,同样的XNamespace使用的时候也符合这种规则。另外,使用 LINQ to XML 中 XPath 功能的 XPath 查询的执行性能比 LINQ to XML 查询低,所以对性能有要求的话尽量避免使用XPath。

6.LINQ to XML安全性 

该部分暂时未在平时工作中涉及到,此次标记出来,以供以后使用 https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml-security

 

本文参考 https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml

posted @ 2017-07-17 09:01  Arthur还在路上  阅读(455)  评论(0编辑  收藏  举报