Linq to XML - 更新/更改XML文档的节点

21 c# xml linq linq-to-xml

我有两个问题:

1.我已经开始使用Linq解决XML问题了,我想知道是否可以通过Linq更改XML文档.我的意思是,有什么喜欢的

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

update item in xmlDoc.Descendants("item")
where (int)item .Attribute("id") == id
...
Run Code Online (Sandbox Code Playgroud)

2.我已经知道如何通过简单地使用创建和添加新的XMLElement

xmlDoc.Element("items").Add(new XElement(......);
Run Code Online (Sandbox Code Playgroud)

但是如何删除单个条目?

XML样本数据:

<items>
  <item id="1" name="sample1" info="sample1 info" web="" />
  <item id="2" name="sample2" info="sample2 info" web="" />
</itmes>
Run Code Online (Sandbox Code Playgroud)

小智 16

谢谢您的回答.一切正常.

就像我的问题的完整性一样,下面的代码显示了如何修改单个条目:

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");
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:你可以跳过StringReader步骤,然后说"XDocument d = XDocument.Parse(xml)". (7认同)

Rob*_*ney 7

这是你的想法吗?

using System;
using System.Linq;
using System.Xml.Linq;

static void Main(string[] args)
{
    string xml = @"<data><record id='1'/><record id='2'/><record id='3'/></data>";
    StringReader sr = new StringReader(xml);
    XDocument d = XDocument.Load(sr);

    // the verbose way, if you will be removing many elements (though in
    // this case, we're only removing one)
    var list = from XElement e in d.Descendants("record")
               where e.Attribute("id").Value == "2" 
               select e;

    // convert the list to an array so that we're not modifying the
    // collection that we're iterating over
    foreach (XElement e in list.ToArray())
    {
       e.Remove();
    }

    // the concise way, which only works if you're removing a single element
    // (and will blow up if the element isn't found)
    d.Descendants("record").Where(x => x.Attribute("id").Value == "3").Single().Remove();

    XmlWriter xw = XmlWriter.Create(Console.Out);
    d.WriteTo(xw);
    xw.Flush();
    Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)