更新并在XML中添加新标记

kin*_*jia 3 c# xelement

以下是我的XML示例:

<Customers>
  <Customer Id="1" Name="abc"/>
  <Customer Id="2" Name="efg"/>
</Customers>
Run Code Online (Sandbox Code Playgroud)

如何使用XElement更新此XML内部?

<Customer Id="1" Name="aaabbbccc"/>
Run Code Online (Sandbox Code Playgroud)

以及如何在这个xml中添加新行?

<Customers>
  <Customer Id="1" Name="abc"/>
  <Customer Id="2" Name="efg"/>
  <Customer Id="3" Name="test"/>
</Customers>
Run Code Online (Sandbox Code Playgroud)

而且,如何获得指定名称?例如,如果为1则为abc,如果为2则为efg

抱歉,我不知道,是XML和XElement的新手.

Sam*_*ach 9

我建议使用LINQ to XML(在命名空间System.Linq和中System.Xml.Linq);

// Load Xml
string xml = "";
XDocument doc = XDocument.Parse(xml);

// Get and modify element
if (doc.Root != null)
{
    var elementToModify = doc.Root.Elements("Customer").SingleOrDefault(x => x.Attribute("Id").Value == "2");
    if (elementToModify != null) elementToModify.SetAttributeValue("Name", "aaabbbccc");
}

// Add new Element
XElement customer = doc.Descendants("Customers").FirstOrDefault();
if (customer != null) customer.Add(new XElement("Customer", new XAttribute("Id", 3), new XAttribute("Name", "test")));

// OR (maddy's answer)
doc.Element("Customers").Add(new XElement("Customer", new XAttribute("Id", 3), new XAttribute("Name", "test")));

// OR (Richard's answer)
doc.Root.LastNode.AddAfterSelf(new XElement("Customer", new XAttribute("Id", 3), new XAttribute("Name", "test")));
Run Code Online (Sandbox Code Playgroud)

编辑:

// Get the Name attribute for a specified Id.
XElement element = doc.Root.Elements("Customer").Single(x => x.Attribute("Id").Value == "1");
string name = element.Attribute("Name").Value; // will be "abc"
Run Code Online (Sandbox Code Playgroud)