我想阅读这篇XML:
<item_proto extended="true" version="1">
<Item vnum="1" name="'y'" gb2312name="Treasure" type="9" subtype="0" weight="0" size="1" antiflag="0" flag="0" wearflag="0" immuneflag="0" gold="0" buy_price="0" limittype0="0" limitvalue0="0" limittype1="0" limitvalue1="0" applytype0="0" applyvalue0="0" applytype1="0" applyvalue1="0" applytype2="0" applyvalue2="0" value0="0" value1="0" value2="0" value3="0" value4="0" value5="0" socket0="0" socket1="0" socket2="0" socket3="0" socket4="0" socket5="0" refine_vnum="11" refine_set="11" magic_pct="0" specular="0" socket_pct="0" />
<Item vnum="2" name="'l'" gb2312name="Key" type="0" subtype="0" weight="0" size="1" antiflag="0" flag="0" wearflag="0" immuneflag="0" gold="0" buy_price="0" limittype0="0" limitvalue0="0" limittype1="0" limitvalue1="0" applytype0="0" applyvalue0="0" applytype1="0" applyvalue1="0" applytype2="0" applyvalue2="0" value0="0" value1="0" value2="0" value3="0" value4="0" value5="0" socket0="0" socket1="0" socket2="0" socket3="0" socket4="0" socket5="0" refine_vnum="11" refine_set="11" magic_pct="0" specular="0" socket_pct="0" />
<Item vnum="19" name="'e9'" gb2312name="Sword" type="1" subtype="0" weight="0" size="2" antiflag="32" flag="1" wearflag="16" immuneflag="0" gold="100" buy_price="750" limittype0="1" limitvalue0="0" limittype1="0" limitvalue1="0" applytype0="7" applyvalue0="22" applytype1="0" applyvalue1="0" applytype2="0" applyvalue2="0" value0="0" value1="15" value2="19" value3="13" value4="15" value5="63" socket0="0" socket1="64992" socket2="127" socket3="64976" socket4="21631" socket5="4855" refine_vnum="0" refine_set="0" magic_pct="15" specular="100" socket_pct="1" />
</item_proto>
如果可能,我想只阅读其中一个节点:gb2312name
。
这是我试过的:
Dim doc As New XmlDocument()
Dim root As XmlNode = doc.GetElementsByTagName("Item").Item(3)
'Display the contents of the child nodes.
If root.HasChildNodes Then
Dim i As Integer
For i = 0 To root.ChildNodes.Count - 1
ListBox1.Items.Add(root.ChildNodes(i).InnerText)
Next i
End If
答案 0 :(得分:2)
让我们从可能导致异常的问题开始:(大多数)集合的索引从零开始,包括这个。因此,如果您想获得第三个<Item>
,那就是.Item(2)
(或只是(2)
):
Dim root As XmlNode = doc.GetElementsByTagName("Item")(2)
接下来,root.ChildNodes
不包含属性,即使这样做,InnerText
也不是正确的属性。幸运的是,Attributes
exists你甚至不需要循环! (顺便说一句,如果你这样做,那将是一个For Each
循环。)
ListBox1.Items.Add(root.Attributes("gb2312name"))
因此,如果您想从每个元素添加gb2312name
,那么它将是:
For Each el In doc.GetElementsByTagName("Item")
ListBox1.Items.Add(el.Attributes("gb2312name"))
Next