二者在通过Load方法加载XML时:
XDocument.Load() 加载整个XML文档 包括根节点
XElement.Load() 不加载XML的根节点.
XElement.Load()
File.WriteAllText("Test.xml", @"<Root>
<Child1>1</Child1>
<Child2>2</Child2>
<Child3>3</Child3>
</Root>");
- Console.WriteLine("Querying tree loaded with XElement.Load");
- Console.WriteLine("----");
-
- XElement doc = XElement.Load("Test.xml");
- IEnumerable<XElement> childList = from el in doc.Elements()
- select el;
-
- foreach (XElement e in childList)
- Console.WriteLine(e);
Querying tree loaded with XElement.Load
- ----
- <Child1>1</Child1>
- <Child2>2</Child2>
- <Child3>3</Child3>
XDocument.Load()
- File.WriteAllText("Test.xml", @"<Root>
- <Child1>1</Child1>
- <Child2>2</Child2>
- <Child3>3</Child3>
- </Root>");
-
- Console.WriteLine("Querying tree loaded with XDocument.Load");
- Console.WriteLine("----");
- XDocument doc = XDocument.Load("Test.xml");
- IEnumerable<XElement> childList = from el in doc.Elements() select el;
-
- foreach (XElement e in childList)
- Console.WriteLine(e);
结果:
- Querying tree loaded with XDocument.Load
- ----
- <Root>
- <Child1>1</Child1>
- <Child2>2</Child2>
- <Child3>3</Child3>
- </Root>