2013-04-15 148 views
2

我想解析XML字符串,像这样的:解析XML得到节点值

<Folk id="4630" country="US" name="Marry" />

(这是摆在富文本编辑器)

并获取idcountryname值。

什么有我想:

Dim content As String = Me.RichTextBox1.Text 
Dim doc As New System.Xml.XmlDocument 

Try 
     doc.LoadXml(content) 
Catch ex As Exception 
     Label2.Text = "No XML Elements!!!!" 
End Try 

Dim items = doc.GetElementsByTagName("Folk") 

For Each item As System.Xml.XmlElement In items 
    Dim id As String = item.ChildNodes(0).InnerText() 
    MsgBox(id) 'Try to prompt a message box containing the id="" 
Next 

它与一个错误显示出来结束了:NullReferenceException was unhandled. - 它不发现id那里,所以我不处理此错误,首先,我想获得正确的回报,那么我会处理,如果没有发现任何东西。那为什么它不返回Folkid=""?对节点的访问是否错误?

回答

1

问题是您在尝试在解析XML后引用XML的方式。

尝试改变这一行:

Dim id As String = item.ChildNodes(0).InnerText() 

以下几点:

Dim id As String = item.Attributes(0) 

countryname将是:

Dim country As String = item.Attributes(1) 
Dim name As String = item.Attributes(2) 

编辑:对不起,我说的C#和vb.net在同一时间即现在修好了。

+0

是的。你是对的,但是如果有多个'',它只是读取第一个。 ': - /'但是至少它的工作...... – Lucas

+0

我想如果有很多''条目,那么他们应该被正确包装在''里,然后你会参考个别的'ChildNodes(x)'你最初的尝试方式。合理? –

+0

语法会变成:'Dim id As String = item.ChildNodes(0).Attributes(0)' –