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

前端 未结 2 1151
情深已故
情深已故 2020-12-23 13:44

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 xml         


        
相关标签:
2条回答
  • 2020-12-23 14:06

    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

    0 讨论(0)
  • 2020-12-23 14:26

    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.

    0 讨论(0)
提交回复
热议问题