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 :(
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")
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With