2010-05-24 102 views
1

嘿,我刚刚在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但它似乎并没有工作。在第一次出现后,它会一直给出错误。我肯定错过了什么?

大卫

+0

你会得到什么错误? – SLaks 2010-05-24 16:43:28

回答

1

你永远不会关闭第一<ip>元素。
因此,当循环重复时,它会尝试读取第一个内部的第二个<ip>

您需要在循环结束时调用ReadEndElement()两次。

+0

感谢您的评论。我在最后添加了两次,但似乎不再循环(只做一次) – StealthRT 2010-05-24 16:53:31

+0

尝试只调用一次。 – SLaks 2010-05-24 17:00:20

+0

是的,试过了,它仍然只显示一个而不是2.给出了和以前一样的错误。 – StealthRT 2010-05-24 17:01:52

1

如果您能够使用.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可以用来从文件加载。