且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

LINQ到XML - 更新/修改XML文档中的节点

更新时间:2023-11-02 11:47:40

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

就像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");