Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to XML Add element to specific sub tree

Tags:

c#

xml

linq

My 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>

I want to add new Account element to lets say Customer with id 2. 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 ?)

My LINQ to XML code:

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");

Thanks for the help. XML is not my good friend :(

like image 972
Safiron Avatar asked Nov 11 '12 17:11

Safiron


1 Answers

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")
                         )
                  );
like image 91
Rohit Vats Avatar answered Oct 08 '22 04:10

Rohit Vats