Question All available xpath in XML document

Snooker

Member
Joined
May 20, 2010
Messages
12
Programming Experience
10+
Hi everyone,
I am using vb.net 2010 to get data from XML file, I was wondering if there is any way to find and print all available xpath of all nodes in the document. For example:
XML file is like :
HTML:
<CATALOG>
  <CD>
    <TITLE>Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
  </CD>
  <CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
  </CD>
</CATALOG>

The result should be something like :

/CATALOG
/CATALOG/CD
/CATALOG/CD/TITLE
/CATALOG/CD/ARTIST

I hope I'm clear enough..
Any help would be highly appreciated.
Thanks in advance.
 
I am working with this right now, This recursive sub can easily find path of all children but it will miss any sibling!

VB.NET:
Imports System.Xml
Public Class Form1
    Public path As String

    Private Sub cmdRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRun.Click
        Dim xDoc As XmlDocument = New XmlDocument
        xDoc.Load("C:\Temp\file.xml")
        Dim node As XmlNode = xDoc.SelectSingleNode("/catalog")
        path = node.Name
        GetPath(node)
    End Sub

    Private Sub GetPath(ByVal node As XmlNode)
        lst.Items.Add(path)

        If node.HasChildNodes = True Then 'If Not node.NodeType = XmlNodeType.Text Then ' <==> 
            path = path & "/" & node.FirstChild.Name
            node = node.FirstChild
            GetPath(node)
        End If
    End Sub

End Class

Hope someone can build on this and give some insights. :mad:
 
VB.NET:
Sub GetPaths(ByVal node As Xml.XmlNode, ByVal paths As List(Of String), Optional ByVal path As String = "")
    path &= "/" & node.Name
    If Not paths.Contains(path) Then paths.Add(path)
    For Each child As Xml.XmlNode In node.ChildNodes
        If child.NodeType = Xml.XmlNodeType.Element Then
            GetPaths(child, paths, path)
        End If
    Next
End Sub
VB.NET:
Dim doc As New Xml.XmlDocument
doc.Load("data.xml")
Dim paths As New List(Of String)
GetPaths(doc.DocumentElement, paths)
 

Latest posts

Back
Top