Linq to XML Add element to specific sub tree

后端 未结 3 745
南笙
南笙 2021-01-11 17:08

My XML:


 
  
   
                         
  

        
相关标签:
3条回答
  • 2021-01-11 17:24
    var cust = xDoc.Descendants("Customer")
                   .First(c => c.Attribute("id").Value == "2");
    cust.Element("Accounts").Add(new XElement("Account", new XAttribute("id","3") ));
    
    0 讨论(0)
  • 2021-01-11 17:31

    You are almost there, your code will be default add the element to the first Customer. You need to search for the attribute id in collection of Customers whose value is 2 -

    document.Element("Bank").Elements("Customer")
            .First(c => (int)c.Attribute("id") == 2).Element("Accounts").Add
                     (
                         new XElement
                             (
                                 "Account", new XAttribute("id", "variable")
                             )
                      );
    
    0 讨论(0)
  • 2021-01-11 17:44

    I know how to add the line what I dont know how do I specify the customer (where do I write the Customer's ID ?)

    You need to find the Customer element with the right ID first. For example:

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

    Note that this will fail on the Single call if there isn't exactly one Customer element with the right ID. If you want to create a new customer, you'll need to do a bit more work - but presumably that would be in a different call anyway.

    0 讨论(0)
提交回复
热议问题