Linq to XML将元素添加到特定子树

Saf*_*ron 9 c# xml linq

我的XML:

<Bank>
 <Customer id="0">
  <Accounts>
   <Account id="0" />
   <Account id="1" />                      
  </Accounts>
 </Customer>
 <Customer id="1">
  <Accounts>
   <Account id="0" />                    
   </Accounts>
 </Customer>
 <Customer id="2">
  <Accounts>
   <Account id="0" />                    
  </Accounts>
 </Customer>
</Bank>
Run Code Online (Sandbox Code Playgroud)

我想添加新的Account元素,让我们说ID为2的客户.我知道如何添加行,我不知道如何指定客户(我在哪里写客户的ID?)

我的LINQ to XML代码:

XDocument document = XDocument.Load("database.xml");
document.Element("Bank").Element("Customer").Element("Accounts").Add
     (
         new XElement
             (
                 "Account", new XAttribute("id", "variable")
             )
      );
document.Save("database.xml");
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助.XML不是我的好朋友:(

Roh*_*ats 21

你几乎就在那里,你的代码将默认添加到第一个元素Customer.您需要id在值为2的Customers集合中搜索该属性-

document.Element("Bank").Elements("Customer")
        .First(c => (int)c.Attribute("id") == 2).Element("Accounts").Add
                 (
                     new XElement
                         (
                             "Account", new XAttribute("id", "variable")
                         )
                  );
Run Code Online (Sandbox Code Playgroud)