I can select the first customer node and change its company name with the code below.
But how do I select customer node where ID=2?
XDocument xmldoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("These are all the customers transfered from the database."),
new XElement("Customers",
new XElement("Customer",
new XAttribute("ID", 1),
new XElement("FullName", "Jim Tester"),
new XElement("Title", "Developer"),
new XElement("Company", "Apple Inc.")
),
new XElement("Customer",
new XAttribute("ID", 2),
new XElement("FullName", "John Testly"),
new XElement("Title", "Tester"),
new XElement("Company", "Google")
)
)
);
XElement elementToChange = xmldoc.Element("Customers").Element("Customer").Element("Company");
elementToChange.ReplaceWith(new XElement("Company", "new company value..."));
Thanks guys, for the record, here is the exact syntax to search out the company element in the customer-with-id-2 element, and then change only the value of the company element:
XElement elementToChange = xmldoc.Element("Customers")
.Elements("Customer")
.Single(x => (int)x.Attribute("ID") == 2)
.Element("Company");
elementToChange.ReplaceWith(
new XElement("Company", "new company value...")
);
Just figured it out in method syntax as well:
XElement elementToChange = (from c in xmldoc.Element("Customers")
.Elements("Customer")
where (int)c.Attribute("ID") == 3
select c).Single().Element("Company");
Assuming the ID is unique:
var result = xmldoc.Element("Customers")
.Elements("Customer")
.Single(x => (int?)x.Attribute("ID") == 2);
You could also use First
, FirstOrDefault
, SingleOrDefault
or Where
, instead of Single
for different circumstances.