Groups | Blog | Home
all groups > dotnet xml > march 2006 >

dotnet xml : How to retreive deepest XPath value from XML using VB.NET


Cerebrus
3/1/2006 6:18:59 AM
Hi Goran,

I don't know how to do this using an XPath expression. But I found this
thread where Dimitre Novatchev gives the answer. Check out the whole
thread if needed.

http://www.biglist.com/lists/xsl-list/archives/200504/msg00390.html

Alternatively, you can do it using the XmlNode class, using it's
HasChildNodes property and looping through the nodes.

HTH,

Regards,

Cerebrus.
Goran Djuranovic
3/1/2006 8:39:09 AM
Hi All,
Does anyone know how to retreive deepest XPath value from XML document =
by using VB.NET? For example, if I had an XML file like this:

<Root>
<Customer>
<Name>MyName</Name>
</Customer>
</Root>

I would like to retreive "\Root\Customer\Name" out of it. Something =
like:
Dim xmlDoc As XMLDocument
Dim strXPath As String =3D xmlDoc.GetXPath()

TIA

Goran Djuranovic
3/1/2006 1:15:21 PM
Hi Martin,
Yes, you are right. I switched "\" & "/".
Luckily, I am not using the namespaces and the code you posted is exactly
what I needed. I am posting VB.NET version below, in case someone else needs
it. And, also, thank you very much.

********************** Begin Code ***********************
Imports System.Xml

Imports System.Xml.XPath

_

Public Class TestXML

'Entry point which delegates to C-style main Private Function

'Public Overloads Shared Sub Main()

' Main(System.Environment.GetCommandLineArgs())

'End Sub

'Public Overloads Shared Sub Main(ByVal args() As String)

' Dim xmlDocument As New XPathDocument("example.xml")

' Dim deepestElement As XPathNavigator = GetDeepestNode(xmlDocument, "*")

' If Not (deepestElement Is Nothing) Then

' Console.WriteLine("Found element {0}.", deepestElement.Name)

' Console.WriteLine(("Path is " + GetXPath(deepestElement)))

' End If

' Dim deepestNode As XPathNavigator = GetDeepestNode(xmlDocument)

' If Not (deepestElement Is Nothing) Then

' Console.WriteLine("Found node of type {0}, value {1}.",
deepestNode.NodeType, deepestNode.Value)

' Console.WriteLine(("Path is " + GetXPath(deepestNode)))

' End If

'End Sub 'Main

Public Sub New()

End Sub

Public Sub GetDeepestXPath()

Dim xmlDocument As New XPathDocument("C:\xmltest.xml")

Dim deepestElement As XPathNavigator = GetDeepestNode(xmlDocument, "*")

If Not (deepestElement Is Nothing) Then

Console.WriteLine("Found element {0}.", deepestElement.Name)

Console.WriteLine(("Path is " + GetXPath(deepestElement)))

End If

Dim deepestNode As XPathNavigator = GetDeepestNode(xmlDocument)

If Not (deepestElement Is Nothing) Then

Console.WriteLine("Found node of type {0}, value {1}.",
deepestNode.NodeType, deepestNode.Value)

Console.WriteLine(("Path is " + GetXPath(deepestNode)))

End If

End Sub



Public Overloads Shared Function GetDeepestNode(ByVal xmlInput As
IXPathNavigable) As XPathNavigator

Return GetDeepestNode(xmlInput, "node()")

End Function 'GetDeepestNode



Public Overloads Shared Function GetDeepestNode(ByVal xmlInput As
IXPathNavigable, ByVal nodeTest As String) As XPathNavigator

Dim xPathNavigator As XPathNavigator = xmlInput.CreateNavigator()

Dim xPathExpression As XPathExpression = xPathNavigator.Compile(("//" +
nodeTest))

xPathExpression.AddSort("count(ancestor::node())", XmlSortOrder.Descending,
XmlCaseOrder.None, "", XmlDataType.Number)

Dim nodeIterator As XPathNodeIterator =
xPathNavigator.Select(xPathExpression)

If nodeIterator.MoveNext() Then

Return nodeIterator.Current

Else

Return Nothing

End If

End Function 'GetDeepestNode



Public Overloads Shared Function GetXPath(ByVal navigator As XPathNavigator)
As String

Return GetXPath(navigator, "")

End Function 'GetXPath



Public Overloads Shared Function GetXPath(ByVal navigator As XPathNavigator,
ByVal currentPath As String) As String

Dim name As String = ""

Select Case navigator.NodeType

Case XPathNodeType.Root

Return "/" + currentPath

Case XPathNodeType.Element

name = navigator.Name

GoTo CaseXPathNodeTypeDotText

Case XPathNodeType.Comment

name = "comment()"

GoTo CaseXPathNodeTypeDotText

Case XPathNodeType.ProcessingInstruction

name = "processing-instruction()"

GoTo CaseXPathNodeTypeDotText

Case XPathNodeType.Text

CaseXPathNodeTypeDotText:

If name = "" Then

name = "text()"

End If

Dim position As Integer =
Convert.ToInt32(CDbl(navigator.Evaluate(("count(preceding-sibling::" + name
+ ")")))) + 1

navigator.MoveToParent()

Dim someString As String

If currentPath <> "" Then

'someString = name & "[" & position & "]" & "/" & currentPath

someString = name & "/" & currentPath

Else

'someString = name & "[" & position & "]"

someString = name

End If

'Return GetXPath(navigator, name + "[" + position + "]" +(If currentPath <>
"" Then "/" + CurrentPath Else "")) 'ToDo: Unsupported feature: conditional
(?) operator.

Return GetXPath(navigator, someString)

Case Else

Return ""

End Select

End Function 'GetXPath

End Class 'Test

************************* End Code *******************************

Thanks

Goran Djuranovic





[quoted text, click to view]
Martin Honnen
3/1/2006 5:18:03 PM


[quoted text, click to view]


[quoted text, click to view]

Well \Root and so on is not even legal XPath syntax, I guess you want
/Root/Customer/Name
but event then in terms of the XPath data model there is a leaf text
node deeper than that element so e.g.
/Root/Customer/Name/text()
or
/Root[1]/Customer[1]/Name[1]/text()[1]
might be more precise to describe/select the deepest node.

I don't have VB.NET code for that, here is some sample C# .NET code that
should do as long as no namespaces are involved:

using System.Xml;
using System.Xml.XPath;

public class Test {
public static void Main (string[] args) {
XPathDocument xmlDocument = new XPathDocument("example.xml");
XPathNavigator deepestElement = GetDeepestNode(xmlDocument, "*");
if (deepestElement != null) {
Console.WriteLine("Found element {0}.", deepestElement.Name);
Console.WriteLine("Path is " + GetXPath(deepestElement));
}
XPathNavigator deepestNode = GetDeepestNode(xmlDocument);
if (deepestElement != null) {
Console.WriteLine("Found node of type {0}, value {1}.",
deepestNode.NodeType, deepestNode.Value);
Console.WriteLine("Path is " + GetXPath(deepestNode));
}
}

public static XPathNavigator GetDeepestNode (IXPathNavigable xmlInput) {
return GetDeepestNode(xmlInput, "node()");
}

public static XPathNavigator GetDeepestNode (IXPathNavigable
xmlInput, string nodeTest) {
XPathNavigator xPathNavigator = xmlInput.CreateNavigator();
XPathExpression xPathExpression = xPathNavigator.Compile("//" +
nodeTest);
xPathExpression.AddSort("count(ancestor::node())",
XmlSortOrder.Descending, XmlCaseOrder.None, "", XmlDataType.Number);
XPathNodeIterator nodeIterator =
xPathNavigator.Select(xPathExpression);
if (nodeIterator.MoveNext()) {
return nodeIterator.Current;
}
else {
return null;
}
}

public static string GetXPath (XPathNavigator navigator) {
return GetXPath(navigator, "");
}

public static string GetXPath (XPathNavigator navigator, string
currentPath) {
string name = "";
switch (navigator.NodeType) {
case XPathNodeType.Root:
return "/" + currentPath;
case XPathNodeType.Element:
name = navigator.Name;
goto case XPathNodeType.Text;
case XPathNodeType.Comment:
name = "comment()";
goto case XPathNodeType.Text;
case XPathNodeType.ProcessingInstruction:
name = "processing-instruction()";
goto case XPathNodeType.Text;
case XPathNodeType.Text:
if (name == "") {
name = "text()";
}
int position =
Convert.ToInt32((double)navigator.Evaluate("count(preceding-sibling::" +
name + ")")) + 1;
navigator.MoveToParent();
return GetXPath(navigator, name + "[" + position + "]" +
(currentPath != "" ? "/" + currentPath : ""));
default:
return "";
}
}

}

If namespaces are involved it gets difficult to simply return a string,
you need to use prefixes then in the XPath expression and somehow return
how those prefixes are bound to namespace URIs.


--

Martin Honnen --- MVP XML
AddThis Social Bookmark Button