我有这个 XML:
<states>
<state name="Alaska" colour="#6D7B8D">
<Location Name="loc1">
<Address>a1</Address>
<DateNTime>a2</DateNTime>
</Location>
<Location Name="loc2">
<Address>b1</Address>
<DateNTime>b2</DateNTime>
</Location>
</state>
<state name="Wyoming" colour="#6D7B8D">
<Location Name="loc3">
<Address>c1</Address>
<DateNTime>c2</DateNTime>
</Location>
<Location Name="loc4">
<Address>d1</Address>
<DateNTime>d2</DateNTime>
</Location>
</state>
</states>
我需要从状态中添加/删除位置。我该怎么做呢?谁能举例说明如何使用 Linq?
最佳答案
Linq 不处理插入或删除。
但是您可以同时使用 XLinq 库。
var doc = XDocument.Load(fileName); // or .Parse(xmlText);
var alaska = doc.Root.Elements("state")
.Where(e => e.Attribute("name").Value == "Alaska").First();
alaska.Add(new XElement("Location", new XAttribute("Name", "someName"),
new XElement("Address", ...)));
关于c# - 在 C# 中从 XML 添加/删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9039181/