var cust = xDoc.Descendants("Customer")
.First(c => c.Attribute("id").Value == "2");
cust.Element("Accounts").Add(new XElement("Account", new XAttribute("id","3") ));
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")
)
);
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.