简体   繁体   English

使用 VB.NET 检索 xml 文件中顶部元素的值

[英]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.我试图在下面的 XML 示例中获取元素totalHits的值,但徒劳无功。 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 文件的其余部分获得了其他元素,但很难获得文件顶部的元素。

XML file: XML文件:

<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.如前所述,您的 XML 示例格式不正确。 I had to fix it.我不得不修复它。 The rest is trivial by using LINQ to XML .通过使用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 |
+------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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