Reputation: 883
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 :(
Upvotes: 12
Views: 18927
Reputation: 81253
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")
)
);
Upvotes: 23
Reputation: 116118
var cust = xDoc.Descendants("Customer")
.First(c => c.Attribute("id").Value == "2");
cust.Element("Accounts").Add(new XElement("Account", new XAttribute("id","3") ));
Upvotes: 0
Reputation: 1500525
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.
Upvotes: 3