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

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

问题描述

我有两个问题:

1.我已经开始使用 Linq to XML,我想知道是否可以通过 Linq 更改 XML 文档.我的意思是,有没有像

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.我已经知道如何通过简单地使用

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 示例数据:

<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 to XML - 更新/更改 XML 文档的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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