LINQ TO XML学习心得(一)

之前没有学习过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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值