在VB Net中获取属性XML

时间:2015-04-11 11:30:43

标签: xml vb.net

我如何在VB.net中获得link2或link3的价值

(我使用节点("链接")。属性(" href")。价值仅获得' link1')

<entry>
        <id>Title</id>
        <link href='link1' />
        <link href='link2' />
        <link href='link3' />
        <link href='link4' />
        <link href='link5' />
</entry>
<entry>
        <id>Title</id>
        <link href='link1' />
        <link href='link2' />
        <link href='link3' />
        <link href='link4' />
        <link href='link5' />
</entry>

我的代码:

    doc.Load(url_get)
    Dim elemList As XmlNodeList = doc.GetElementsByTagName("entry")
    Dim node As XmlElement = Nothing
    For Each node In elemList
       'code....
    NEXT

4 个答案:

答案 0 :(得分:1)

您可以从XML片段创建一个XElement,然后从第二个和第三个链接元素中获取href属性。

Dim ent As XElement = <entry>
                          <id>Title</id>
                          <link href='link1'/>
                          <link href='link2'/>
                          <link href='link3'/>
                          <link href='link4'/>
                          <link href='link5'/>
                      </entry>

Dim links As IEnumerable(Of XElement) = ent.<link>
Dim link2, link3 As String
If links.Count > 2 Then
    link2 = links(1).@href
    link3 = links(2).@href
End If

[编辑:基于对另一个答案的评论]。如果要循环链接2到3(假设它们存在),可以使用以下代码:

Dim ent As XElement =
    <entry>
        <id>Title</id>
        <link href='link1'/>
        <link href='link2'/>
        <link href='link3'/>
        <link href='link4'/>
        <link href='link5'/>
    </entry>

For i As Integer = 1 To Math.Min(2, ent.<link>.Count - 1)
    Dim link As String = ent.<link>(i).@href
    'Do something with link
Next

答案 1 :(得分:1)

考虑到你有这个:

    Dim xml As XElement =
        <entry>
            <id>Title</id>
            <link href='link1'/>
            <link href='link2'/>
            <link href='link3'/>
            <link href='link4'/>
            <link href='link5'/>
        </entry>

然后你可以得到第一个和第二个值:

    Dim value1 As String = xml.<link>(0).@href
    Dim value2 As String = xml.<link>(1).@href

答案 2 :(得分:0)

试试这个:

dim xDoc as New XMLDocument
xDoc.LoadXML("<entry><id>Title</id><link href='link1' /><link href='link2' />" & 
    "<link href='link3' /><link href='link4' /><link href='link5' />" &
    "</entry>")
dim s As String = xDoc.SelectSingleNode("(/entry/link)[2]").Attributes("href").value

这是第二个链接。

或者像这样:

dim xn as XmlNodeList = xDoc.SelectNodes("/entry/link")
dim s As String = xn(1).Attributes("href").value

这也是第二个(从0开始)。

答案 3 :(得分:0)

根据您发布的代码获取所有href的一种可能方法:

doc.Load(url_get)
Dim elemList As XmlNodeList = doc.GetElementsByTagName("entry")
Dim node As XmlElement = Nothing
For Each node In elemList
   For Each href As XmlNode In node.SelectNodes("link/@href")
        Console.WriteLine(href.Value)
    Next
Next