tags:

views:

6937

answers:

2

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

ANSWER:

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

ANSWER WITH METHOD SYNTAX:

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");
+9  A: 

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.

Mehrdad Afshari
why does this give me the error: System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' does not contain a definition for 'Single' and no extension method 'Single' accepting a first argument of type 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' found
Edward Tanguay
Do you have `using System.Linq` on top of your source?
Mehrdad Afshari
I do now! Thanks. :-)
Edward Tanguay
+1  A: 

I'd use something like:

dim customer = (from c in xmldoc...<Customer> 
                where c.<ID>.Value=22 
                select c).SingleOrDefault

Edit:

missed the c# tag, sorry......the example is in VB.NET

Nick