嘿,我对VB.net上的XML解析还是个新手。这是我用来解析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,但它似乎不起作用。在第一次循环之后,它一直给出一个错误。我一定漏掉了什么?
大卫
发布于 2010-05-27 07:38:58
如果您能够使用XML3.5,我建议您使用.NET文本和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可以用来从文件中加载。
https://stackoverflow.com/questions/2898548
复制相似问题