获取节点名称 XML 文件的属性

Get Name of Nodes Attributes of an XML file

提问人:Marco Giglio 提问时间:9/23/2023 更新时间:9/23/2023 访问量:26

问:

我正在尝试获取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>

我正在尝试获取“姓氏”、“名称”、“colorB”、“colorA”等。

我 vb.net 示例中这样做,但我无法获得属性(需要类似阅读器的东西。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
XML vb.net 属性 节点

评论

0赞 LMC 9/23/2023
对属性也有效:stackoverflow.com/a/7984537/2834978name(//path/to/@attribute)

答:

0赞 dbasnett 9/23/2023 #1

看看这是否有帮助

Dim xe As XElement ' = XElement.Load(filePath) 'for production
' for testing used literal
xe = <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>

Dim nms As New List(Of String)

'get body nodes attributes names

nms = (From el In xe...<body>
         From attr In el.Attributes
           Select attr.Name.LocalName).ToList

如果只希望属性名称出现一次,请更改 。ToList 更改为 。Distinct.ToList(独特.ToList)