从XML节点读取值

时间:2016-02-15 10:19:00

标签: xml vb.net

XML文件的格式

<Main>
    <Item>
         <ProductDescription ID="123" LongDescription="Text" Langid="1">
    </Item>
</Main>

我正在尝试从XML文件中获取LongDescription值(Text)

我使用的代码

    Dim doc As New XmlDocument()
    doc.Load(path)
    Dim xNList As XmlNodeList = doc.SelectNodes("//Main/Item/ProductDescription")
    For Each xNode As XmlNode In xNList
        MsgBox(xNode.OuterXml)
    Next

我得到的结果是

<ProductDescription ID="123" LongDescription="Text" Langid="1">

但我只想提前感谢文字

抱歉打字错误

1 个答案:

答案 0 :(得分:0)

您已在xNode中拥有该元素。您所要做的就是访问属性LongDescription。最简单的方法是将xNode投射到XmlElement并使用GetAttribute - 方法:

Dim doc As New XmlDocument()
doc.Load(path)
Dim xNList As XmlNodeList = doc.SelectNodes("//Main/Item/ProductDescription")
For Each xNode As XmlNode In xNList
    Dim longDesc = DirectCast(xNode, XmlElement).GetAttribute("LongDescription")
    MsgBox(longDesc)      
Next