Click here to Skip to main content
16,018,904 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello, I'm trying to get names of attributes nodes of an XML file..i'm able to read nodes and attributes value but not names.
In this xml example:
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>

I'm trying to get "surname", "name", "colorB", "colorA" etc.

I do this vb.net example but I cannot get attribute (need something like a reader.GetNameAttribute command)? Does it exists?

What I have tried:

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"



    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
Posted

1 solution

Hello,

you could be using the class XmlNode see here: XmlNode Class (System.Xml) | Microsoft Learn[^]

Refactoring a bit your code like that:
While reader.Read

    Dim lettura = reader.NodeType
    Dim valueA As String
    Dim attr_name As String = "none"

    valueA = reader.Name
    If reader.HasAttributes Then
        Dim node As XmlNode = docXML.ReadNode(reader)
        Console.Write("Node is: " & valueA)

        If node.Attributes IsNot Nothing Then
            For Each attribute As XmlAttribute In node.Attributes
                Console.Write(" Attribute Name: {0}, Value: {1}.", attribute.Name, attribute.Value)
            Next
        End If
        Console.WriteLine()
    End If
End While

Console.Read()


gives you this output:

Node is: xml
Node is: body Attribute Name: surname, Value: Rott. Attribute Name: name, Value: Pig.
Node is: body Attribute Name: colorB, Value: White. Attribute Name: colorA, Value: Yellow.


Good luck!
Valery
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900