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

前端 未结 2 1154
情深已故
情深已故 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: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.

提交回复
热议问题