VB.NET XML解析器循环
问题描述:
嘿,我刚刚在VB.net上解析XML。这是我使用解析XML文件,我的代码:VB.NET XML解析器循环
Dim output As StringBuilder = New StringBuilder()
Dim xmlString As String = _
"<ip_list>" & _
"<ip>" & _
"<ip>192.168.1.1</ip>" & _
"<ping>9 ms</ping>" & _
"<hostname>N/A</hostname>" & _
"</ip>" & _
"<ip>" & _
"<ip>192.168.1.6</ip>" & _
"<ping>0 ms</ping>" & _
"<hostname>N/A</hostname>" & _
"</ip>" & _
"</ip_list>"
Using reader As XmlReader = XmlReader.Create(New StringReader(xmlString))
'reader.ReadStartElement("ip_list")
Do Until reader.EOF
reader.ReadStartElement("ip_list")
reader.ReadStartElement("ip")
reader.ReadStartElement("ip")
reader.MoveToFirstAttribute()
Dim theIP As String = reader.Value.ToString
reader.ReadToFollowing("ping")
Dim thePing As String = reader.ReadElementContentAsString().ToString
reader.ReadToFollowing("hostname")
Dim theHN As String = reader.ReadElementContentAsString().ToString
MsgBox(theIP & " " & thePing & " " & theHN)
reader.ReadEndElement()
Loop
reader.Close()
End Using
我把自己do until reader.EOF
但它似乎并没有工作。在第一次出现后,它会一直给出错误。我肯定错过了什么?
大卫
答
如果您能够使用.NET 3.5,我会推荐使用XML文字和LINQ语法。
Dim ips = From xe In XElement.Parse(xmlString).<ip> _
Select New With {.IP = xe.<ip>.Value, _
.Ping = xe.<ping>.Value, _
.HostName = xe.<hostname>.Value}
'if you only want one
Dim firstIp = ips.First()
还有一个XElement.Load
可以用来从文件加载。
你会得到什么错误? – SLaks 2010-05-24 16:43:28