How to get value of child node from XDocument

前端 未结 2 372
无人共我
无人共我 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

    <Father>
        <Child>Hello</Child>
        <Child>World!</Child>
    </Father>
    

    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;
    
    0 讨论(0)
  • 2020-12-10 01:55

    If there's only one Cust element and only one ACTNumber element, then it's easy:

    string actNumber = doc.Root.Element("Cust").Element("ACTNumber").Value;
    

    Or to get it as a long:

    long actNumber = (long) doc.Root.Element("Cust").Element("ACTNumber");
    
    0 讨论(0)
提交回复
热议问题