加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:27:32 所属栏目:百科 来源:网络整理
导读:我的 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 我想添加新的Acc
我的 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")
                         )
                  );

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读