简体   繁体   中英

How to select a specific node with LINQ-to-XML

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM