470,586 Members | 1,346 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,586 developers. It's quick & easy.

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

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 = xmlDoc.GetXPath()

TIA

Goran Djuranovic
Mar 1 '06 #1
3 6530
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-lis.../msg00390.html

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

HTH,

Regards,

Cerebrus.

Mar 1 '06 #2


Goran Djuranovic wrote:

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.


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
http://JavaScript.FAQTs.com/
Mar 1 '06 #3
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(pr eceding-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

"Martin Honnen" <ma*******@yahoo.de> wrote in message
news:uC**************@TK2MSFTNGP14.phx.gbl...


Goran Djuranovic wrote:

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.


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
http://JavaScript.FAQTs.com/

Mar 1 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by bdinmstig | last post: by
4 posts views Thread by Son KwonNam | last post: by
5 posts views Thread by Jeroen Ceuppens | last post: by
9 posts views Thread by David Thielen | last post: by
reply views Thread by Goran Djuranovic | last post: by
3 posts views Thread by Jason Mobarak | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.