简体   繁体   中英

Retrieve value of top element in xml file with VB.NET

I am trying to get the value of the element totalHits in the XML example below but in vain. I get the other elements in the rest of the XML file but struggle to get the one at the top of the file.

XML file:

<result xmlns="urn:com:tradedoubler:pf:model:xml:output" xmlns:ns2="urn:com:tradedoubler:pf:model:xml:common" version="3.0">
<productHeader>
<totalHits>4907</totalHits>
</productHeader>
<products>

I tried using:

doc.SelectSingleNode("result/productHeader/totalHits").innerText

Any help would be appreciated.

As mentioned earlier, your XML sample is not well-formed. I had to fix it. The rest is trivial by using LINQ to XML .

VB.NET

Sub Main
    Dim myXml As XElement = <result xmlns="urn:com:tradedoubler:pf:model:xml:output"
        xmlns:ns2="urn:com:tradedoubler:pf:model:xml:common" version="3.0">
    <productHeader>
        <totalHits>4907</totalHits>
    </productHeader>
</result>

    Dim ns1 As XNamespace = "urn:com:tradedoubler:pf:model:xml:output"
    Console.WriteLine(myXml.Descendants(ns1 + "productHeader").Elements(ns1 + "totalHits").Value)
End Sub

Output

+------+
| 4907 |
+------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM