How to get value of child node from XDocument

前端 未结 2 383
无人共我
无人共我 2020-12-10 01:12

I need to get value of child node from XDocument using linq



     1234
     
2条回答
  •  渐次进展
    2020-12-10 01:50

    Use this:

    xDocTest.Root.Element("Cust").Element("Adress").Element("City").Value
    

    If you use Elements (note the plural) it gives u an IEnumerable, this would be used like this:

    XML

    
        Hello
        World!
    
    

    C#

    foreach(var childElement in Root.Elements("Child")) Console.WriteLine(childElement.Value);
    

    Or to take your example:

    foreach(var child in xdoc.Root.Element("Cust").Element("Address").Elements()) 
        Console.WriteLine(string.Format("{0} : {1}", child.Name, child.Value);
    

    Im not sure how Element behaves if you have multiple Elements of the same name. So you might want to use Elements and Inerate over all occurences.

    And in Linq If there is more than one Customer...

    var result = from cust in xdoc.Root.Elements("Cust")
    
                 where cust.Elements("ACTNumber").Any() // This is to make sure there
                                                        // is an element called ACTNumber
                                                        // otherwise .Value would create
                                                        // Nullrefexception.
    
                 select child.Element("ACTNumber").Value;
    

提交回复
热议问题