您的位置:首页 > 其它

LINQ TO XML学习心得(一)

2015-12-30 21:32 417 查看
之前没有学习过XML,这次学习完全是重新开始,主要是以MSDN的教程为主。

网址:https://msdn.microsoft.com/zh-cn/library/bb387098.aspx


一、XDocument 与XElement的区别

File.WriteAllText("Test.xml", @"<Root>
<Child1>1</Child1>
<Child2>2</Child2>
<Child3>3</Child3>
</Root>");

XElement doc = XElement.Load("Test.xml");
IEnumerable<XElement> childList =
from el in doc.Elements()
select el;
foreach (XElement e in childList)
Console.WriteLine(e);

展示结果为:

<Child1>1</Child1>
<Child2>2</Child2>
<Child3>3</Child3>

XDocument doc = XDocument.Load("Test.xml");

IEnumerable<XElement> childList =
from el in doc.Elements()
select el;
foreach (XElement e in childList)
Console.WriteLine(e);


得出结果为:

<Root>
<Child1>1</Child1> <Child2>2</Child2> <Child3>3</Child3>
</Root>

用XDocument.Load()的输出会有"Root"节点。

二、三种删除Element的方式:

First, it removes a single element.Second, it retrieves a collection of elements, materializes them using the Enumerable.ToList<TSource> operator, and removes the collection.Finally, it retrieves a collection of elements and removes them using the Remove extension method.

1、删除单个Element节点。找到Element,使用Remove()

2、将Elements转换成List,再删除

3、找到Elements(),再删除

root.Element("Child1").Element("GrandChild1").Remove();
root.Element("Child2").Elements().ToList().Remove();
root.Element("Child3").Elements().Remove();
三、维持键/值  SetAttributeValue and SetElementValue 
1、如果属性或节点不存在,则创建为新的

2、如果已经存在,则修改为新值

3、如果将Value设为null,则删除该节点或属性

四、在查询XML Tree的时候,一定要明白检索到哪一个Element。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: