【问题标题】:Linq to XML Add element to specific sub treeLinq to XML 将元素添加到特定的子树
【发布时间】:2012-10-31 06:52:19
【问题描述】:

我的 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 不是我的好朋友 :(

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    您快到了,您的代码将默认将元素添加到第一个Customer。您需要在值为2的客户集合中搜索属性id -

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

    【讨论】:

    • 这个非常好用,非常感谢。现在我知道该怎么做了
    • 谢谢,罗希特。我一直在尝试访问多个大子节点,这在尝试了大多数失败的解决方案后对我有所帮助。
    【解决方案2】:

    我知道如何添加我不知道如何指定客户的行(我在哪里写客户的 ID?)

    您需要首先找到具有正确 ID 的 Customer 元素。例如:

    var customer = document.Root
                           .Elements("Customer")
                           .Single(x => (int) x.Attribute("id") == id);
    customer.Element("Accounts").Add(new XElement("Account",
                                                  new XAttribute("id", "variable")));
    

    请注意,如果没有一个具有正确 ID 的 Customer 元素,这将在 Single 调用中失败。如果你想创建一个客户,你需要做更多的工作——但大概这会是另外一个电话。

    【讨论】:

      【解决方案3】:
      var cust = xDoc.Descendants("Customer")
                     .First(c => c.Attribute("id").Value == "2");
      cust.Element("Accounts").Add(new XElement("Account", new XAttribute("id","3") ));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多