Jak wybrać konkretny węzeł za pomocą LINQ-to-XML

Mogę wybrać pierwszy węzeł klienta i zmienić nazwę firmy za pomocą poniższego kodu.

Ale jak wybrać węzeł klienta, gdzie 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..."));

Odpowiedź:

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

ODPOWIEDŹ ZE SKŁADNIĄ METODY:

Po prostu zorientowałem się również w składni metody:

XElement elementToChange = (from c in xmldoc.Element("Customers")
                                .Elements("Customer")
                            where (int)c.Attribute("ID") == 3
                            select c).Single().Element("Company");
Author: Edward Tanguay, 2009-02-27

2 answers

Zakładając, że ID jest unikalne:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

Możesz również użyć First, FirstOrDefault, SingleOrDefault lub Where, zamiast Single w różnych okolicznościach.

 45
Author: Mehrdad Afshari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-27 10:49:18

Użyłbym czegoś takiego:

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

Edit:

Przegapiłem tag c#, przepraszam......przykład jest w VB.NET

 4
Author: Nick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-27 10:44:33