473,233 Members | 1,504 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,233 software developers and data experts.

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 6749
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: bdinmstig | last post by:
I refined my attempt a little further, and the following code does seem to work, however it has 2 major problems: 1. Very limited support for XPath features Basic paths are supported for...
4
by: Son KwonNam | last post by:
In XSLT, is this possible to get value from xml using XPath which is in XSLT variable? I mean XPath strings can be dynamic while XSL Transforming. If possible, How?? Because I'm not a...
5
by: Jeroen Ceuppens | last post by:
I need to put a new node at the end of the tree, that end is not te lowest in de list but the deepest (the one with the most + before it) Node A Node 1 Node 2 Node 3 Node 4: Deepest Node B:...
9
by: David Thielen | last post by:
Hi; I am sure I am missing something here but I cannot figure it out. Below I have a program and I cannot figure out why the xpath selects that throw an exception fail. From what I know they...
3
by: Goran Djuranovic | last post by:
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>...
0
by: Goran Djuranovic | last post by:
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>...
3
by: Jason Mobarak | last post by:
Hello -- I'm attempting to get a handle on how to do xpath queries with System.Xml -- so far the biggest hurdle has been how to deal with a default namespace. If I use the test xml: <?xml...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.