微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/csharp/98553.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐