如何在VB.NET中获取XML文件的节点属性名称?
问题
我能够读取XML文件的节点及属性值,但无法获取属性名称。以下为XML示例:
<?xml version="1.0" encoding="UTF-8"?> <Root> <body surname="Rott" name="Pig"> <city>London</city> </body> <body surname="Lip" name="Jack"> <city>Los Angeles</city> </body> <body colorB="White" colorA="Yellow"> <city>Rome</city> </body> </Root>
我想要提取出surname、name、colorB、colorA这类属性名称。我尝试用VB.NET编写了如下代码,但找不到类似reader.GetNameAttribute()的方法来获取属性名称,请问是否存在这样的方法?
OpenFileDialog1.Multiselect = False OpenFileDialog1.ShowDialog() Dim fileName As String = Path.GetFileName(OpenFileDialog1.FileName) Dim filePath As String = OpenFileDialog1.FileName Me.Text = filePath Dim docXML As New XmlDocument docXML.Load(filePath) Dim reader As XmlNodeReader = New XmlNodeReader(docXML) While reader.Read Dim lettura = reader.NodeType Dim valueA As String Dim attr_name As String = "none" 'attr_name = reader.GetNameAttribute() here ? get name attribute???? valueA = reader.Name If reader.HasAttributes Then Dim conteggio As Integer = reader.AttributeCount For x = 0 To conteggio - 1 MsgBox("Node is: " + valueA + " and has an attribute named: " + attr_name + " = " + reader.GetAttribute(x)) Next End If End While
解决方案
方法1:修改现有XmlNodeReader代码
你可以使用XmlNodeReader.MoveToAttribute(index)方法定位到指定索引的属性,然后通过reader.Name获取该属性的名称,修改后的代码如下:
OpenFileDialog1.Multiselect = False OpenFileDialog1.ShowDialog() Dim fileName As String = Path.GetFileName(OpenFileDialog1.FileName) Dim filePath As String = OpenFileDialog1.FileName Me.Text = filePath Dim docXML As New XmlDocument docXML.Load(filePath) Dim reader As XmlNodeReader = New XmlNodeReader(docXML) While reader.Read Dim valueA As String = reader.Name If reader.HasAttributes Then Dim conteggio As Integer = reader.AttributeCount For x = 0 To conteggio - 1 ' 移动到指定索引的属性 reader.MoveToAttribute(x) ' 获取属性名称和值 Dim attr_name As String = reader.Name Dim attr_value As String = reader.Value MsgBox("Node is: " + valueA + " and has an attribute named: " + attr_name + " = " + attr_value) ' 移回原节点,避免后续读取出错 reader.MoveToElement() Next End If End While
方法2:直接遍历XmlDocument的节点属性(更简洁)
如果不需要使用XmlNodeReader,直接通过XmlDocument的节点集合遍历属性会更直观,代码也更易维护:
OpenFileDialog1.Multiselect = False OpenFileDialog1.ShowDialog() Dim filePath As String = OpenFileDialog1.FileName Me.Text = filePath Dim docXML As New XmlDocument docXML.Load(filePath) ' 遍历所有body节点 For Each bodyNode As XmlNode In docXML.SelectNodes("//body") Dim nodeName As String = bodyNode.Name ' 遍历当前节点的所有属性 For Each attr As XmlAttribute In bodyNode.Attributes MsgBox("Node is: " + nodeName + " and has an attribute named: " + attr.Name + " = " + attr.Value) Next Next
内容的提问来源于stack exchange,提问作者Marco Giglio
相关产品推荐
相关产品推荐

