vb.net 解析 XML 以获取节点值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16006732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:15:29  来源:igfitidea点击:

Parse XML to get node value

xmlvb.netxml-parsing

提问by Lucas

I want to parse XML string like this one:

我想像这样解析 XML 字符串:

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

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

(which is placed in the rich textbox editor)

(放置在富文本框编辑器中)

And fetch the id, country, namevalues.

并获取id, country,name值。

What have I tried:

我试过什么:

 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

It does ends up with an error showing up: NullReferenceException was unhandled.- it doesnt found the idthere, so I dont handle this error, first I would like to get the proper return, then I will handle if there is nothing found. So why it doesnt return the Folkid=""? Is the access to the node called wrong?

它最终会出现一个错误:NullReferenceException was unhandled.- 它没有在id那里找到,所以我不处理这个错误,首先我想得到正确的回报,然后我会处理如果没有找到任何东西。那么为什么它不返回Folkid=""?对节点的访问调用是错误的吗?

采纳答案by David Tansey

The problem is the way that you are trying to reference the XML after it has been parsed.

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

Try changing this line:

尝试更改此行:

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

To the following:

对以下内容:

Dim id As String = item.Attributes(0)

countryand namewould be:

country并且name将是:

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

edit:sorry, I was speaking c# and vb.net at the same time. now fixed.

编辑:抱歉,我同时在说 c# 和 vb.net。现在固定。