What's the difference between XElement and XDocument?

前端 未结 4 865
鱼传尺愫
鱼传尺愫 2020-12-29 04:09

What is the difference between XElement and XDocument and when do you use each?

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 04:15

    Here's a practical example from msdn which makes it clear. Assume you have this in test.xml file:

    
        1
        2
        3
    
    
    1. With XDocument if you do this:

      foreach (var element in XDocument.Load("test.xml").Elements())
          Console.WriteLine(element);
      

      You get this back:

      
          1
          2
          3
      
      

      To get the value at Child1 node, you will have to do:

      var child1 = XDocument.Load("test.xml").Element("Root").Element("Child1").Value;
      

      Or

      var child1 = XDocument.Load("test.xml").Root.Element("Child1").Value;
      
    2. With XElement if you do this:

      foreach (var element in XElement.Load("test.xml").Elements())
          Console.WriteLine(element);
      

      You get this back:

      1
      2
      3
      

      To get the value at Child1 node, you will do:

      var child1 = XElement.Load("test.xml").Element("Child1").Value;
      

    In short, XElement ignores the root node while XDocument doesnt. Roughly, XDocument.Root = XElement, or XDocument.Root.Elements() = XElement.Elements(). Both derive from XContainer. Another minor difference is that XElement implements IXmlSerializable which I dont think matters mostly. XElement would be enough for vast majority of cases where you just want to query the sub nodes. The name confuses me though, so I prefer to use XDocument.

提交回复
热议问题