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

前端之家收集整理的这篇文章主要介绍了c# – Linq to XML将元素添加到特定子树前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的 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>

我想添加新的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");

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

解决方法

您几乎就在那里,您的代码将默认添加元素给第一个Customer.您需要在值为2的Customers集合中搜索属性id –
document.Element("Bank").Elements("Customer")
        .First(c => (int)c.Attribute("id") == 2).Element("Accounts").Add
                 (
                     new XElement
                         (
                             "Account","variable")
                         )
                  );
原文链接:https://www.f2er.com/csharp/98553.html

猜你在找的C#相关文章