473,387 Members | 1,534 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,387 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 6757
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

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.