如何使用LINQ-to-XML选择特定节点

时间:2009-02-27 10:31:24

标签: c# linq-to-xml

我可以选择第一个客户节点,并使用以下代码更改其公司名称。

但是如何选择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..."));

解答:

谢谢大家,为了记录,这里是在customer-with-id-2元素中搜索company元素的确切语法,然后只更改company元素的值:

XElement elementToChange = xmldoc.Element("Customers")
    .Elements("Customer")
    .Single(x => (int)x.Attribute("ID") == 2)
    .Element("Company");
elementToChange.ReplaceWith(
    new XElement("Company", "new company value...")
    );

方法语法答案:

在方法语法中也是如此:

XElement elementToChange = (from c in xmldoc.Element("Customers")
                                .Elements("Customer")
                            where (int)c.Attribute("ID") == 3
                            select c).Single().Element("Company");

2 个答案:

答案 0 :(得分:46)

假设ID是唯一的:

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

您还可以使用FirstFirstOrDefaultSingleOrDefaultWhere,而不是Single用于不同的情况。

答案 1 :(得分:4)

我会使用类似的东西:

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

编辑:

错过了c#标签,抱歉......示例是在VB.NET中