LINQ到XML - 更新/修改XML文档中的节点 [英] Linq to XML - update/alter the nodes of an XML Document

查看:167
本文介绍了LINQ到XML - 更新/修改XML文档中的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个问题:

1。
我sarted工作与周围的LINQ to XML,我想知道是否有可能通过LINQ到更改的XML文档。我的意思是,有没有像成才

 的XDocument xmlDoc中= XDocument.Load(sample.xml中);在xmlDoc.Descendants更新项目(项目)
其中(INT)属性约项(ID)== ID
...

2。
我已经知道如何创建和使用简单的增加一个新的XmlElement

  xmlDoc.Element(项目)加入(新的XElement(......);

但我怎么能删除单个条目?

XML样本数据:

 <项目>
  <项目ID =1NAME =SAMPLE1信息=SAMPLE1信息网络=/>
  <项目编号=2NAME =SAMPLE2信息=SAMPLE2信息网络=/>
< / itmes>


解决方案

感谢您的回答。一切工作正常。

就像completition我的问题code以下说明如何修改一个条目:

 字符串XML = @<数据><记录id =1信息=样品信息/><记录id ='2'信息='样本信息/><记录id ='3'信息=样品信息/>< /数据>中;
StringReader SR =新StringReader(XML);
的XDocument D = XDocument.Load(SR);
d.Descendants(记录),其中(X =方式> x.Attribute(ID)值==2)单()SetAttributeValue(信息,新样品信息)。;

I've got 2 Questions:

1. I've sarted working around with Linq to XML and i'm wondering if it is possible to change an XML document via Linq. I mean, is there someting like

XDocument xmlDoc = XDocument.Load("sample.xml");

update item in xmlDoc.Descendants("item")
where (int)item .Attribute("id") == id
...

2. I already know how to create and add a new XMLElement by simply using

xmlDoc.Element("items").Add(new XElement(......);

but how can I remove a single entry?

XML sample data:

<items>
  <item id="1" name="sample1" info="sample1 info" web="" />
  <item id="2" name="sample2" info="sample2 info" web="" />
</itmes>

解决方案

thank you for your answer. everything works fine.

just as completition to my questions the code below shows how to modify a single entry:

string xml = @"<data><record id='1' info='sample Info'/><record id='2' info='sample Info'/><record id='3' info='sample Info'/></data>";
StringReader sr = new StringReader(xml);
XDocument d = XDocument.Load(sr);


d.Descendants("record").Where(x => x.Attribute("id").Value == "2").Single().SetAttributeValue("info", "new sample info");

这篇关于LINQ到XML - 更新/修改XML文档中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆