473,725 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6805
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.XPat h;

public class Test {
public static void Main (string[] args) {
XPathDocument xmlDocument = new XPathDocument(" example.xml");
XPathNavigator deepestElement = GetDeepestNode( xmlDocument, "*");
if (deepestElement != null) {
Console.WriteLi ne("Found element {0}.", deepestElement. Name);
Console.WriteLi ne("Path is " + GetXPath(deepes tElement));
}
XPathNavigator deepestNode = GetDeepestNode( xmlDocument);
if (deepestElement != null) {
Console.WriteLi ne("Found node of type {0}, value {1}.",
deepestNode.Nod eType, deepestNode.Val ue);
Console.WriteLi ne("Path is " + GetXPath(deepes tNode));
}
}

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

public static XPathNavigator GetDeepestNode (IXPathNavigabl e
xmlInput, string nodeTest) {
XPathNavigator xPathNavigator = xmlInput.Create Navigator();
XPathExpression xPathExpression = xPathNavigator. Compile("//" +
nodeTest);
xPathExpression .AddSort("count (ancestor::node ())",
XmlSortOrder.De scending, XmlCaseOrder.No ne, "", XmlDataType.Num ber);
XPathNodeIterat or nodeIterator =
xPathNavigator. Select(xPathExp ression);
if (nodeIterator.M oveNext()) {
return nodeIterator.Cu rrent;
}
else {
return null;
}
}

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

public static string GetXPath (XPathNavigator navigator, string
currentPath) {
string name = "";
switch (navigator.Node Type) {
case XPathNodeType.R oot:
return "/" + currentPath;
case XPathNodeType.E lement:
name = navigator.Name;
goto case XPathNodeType.T ext;
case XPathNodeType.C omment:
name = "comment()" ;
goto case XPathNodeType.T ext;
case XPathNodeType.P rocessingInstru ction:
name = "processing-instruction()";
goto case XPathNodeType.T ext;
case XPathNodeType.T ext:
if (name == "") {
name = "text()";
}
int position =
Convert.ToInt32 ((double)naviga tor.Evaluate("c ount(preceding-sibling::" +
name + ")")) + 1;
navigator.MoveT oParent();
return GetXPath(naviga tor, 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.XPat h

_

Public Class TestXML

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

'Public Overloads Shared Sub Main()

' Main(System.Env ironment.GetCom mandLineArgs())

'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.WriteLi ne("Found element {0}.", deepestElement. Name)

' Console.WriteLi ne(("Path is " + GetXPath(deepes tElement)))

' End If

' Dim deepestNode As XPathNavigator = GetDeepestNode( xmlDocument)

' If Not (deepestElement Is Nothing) Then

' Console.WriteLi ne("Found node of type {0}, value {1}.",
deepestNode.Nod eType, deepestNode.Val ue)

' Console.WriteLi ne(("Path is " + GetXPath(deepes tNode)))

' 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.WriteLi ne("Found element {0}.", deepestElement. Name)

Console.WriteLi ne(("Path is " + GetXPath(deepes tElement)))

End If

Dim deepestNode As XPathNavigator = GetDeepestNode( xmlDocument)

If Not (deepestElement Is Nothing) Then

Console.WriteLi ne("Found node of type {0}, value {1}.",
deepestNode.Nod eType, deepestNode.Val ue)

Console.WriteLi ne(("Path is " + GetXPath(deepes tNode)))

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.Create Navigator()

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

xPathExpression .AddSort("count (ancestor::node ())", XmlSortOrder.De scending,
XmlCaseOrder.No ne, "", XmlDataType.Num ber)

Dim nodeIterator As XPathNodeIterat or =
xPathNavigator. Select(xPathExp ression)

If nodeIterator.Mo veNext() Then

Return nodeIterator.Cu rrent

Else

Return Nothing

End If

End Function 'GetDeepestNode

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

Return GetXPath(naviga tor, "")

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.NodeT ype

Case XPathNodeType.R oot

Return "/" + currentPath

Case XPathNodeType.E lement

name = navigator.Name

GoTo CaseXPathNodeTy peDotText

Case XPathNodeType.C omment

name = "comment()"

GoTo CaseXPathNodeTy peDotText

Case XPathNodeType.P rocessingInstru ction

name = "processing-instruction()"

GoTo CaseXPathNodeTy peDotText

Case XPathNodeType.T ext

CaseXPathNodeTy peDotText:

If name = "" Then

name = "text()"

End If

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

navigator.MoveT oParent()

Dim someString As String

If currentPath <> "" Then

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

someString = name & "/" & currentPath

Else

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

someString = name

End If

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

Return GetXPath(naviga tor, someString)

Case Else

Return ""

End Select

End Function 'GetXPath

End Class 'Test

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

Thanks

Goran Djuranovic

"Martin Honnen" <ma*******@yaho o.de> wrote in message
news:uC******** ******@TK2MSFTN GP14.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.XPat h;

public class Test {
public static void Main (string[] args) {
XPathDocument xmlDocument = new XPathDocument(" example.xml");
XPathNavigator deepestElement = GetDeepestNode( xmlDocument, "*");
if (deepestElement != null) {
Console.WriteLi ne("Found element {0}.", deepestElement. Name);
Console.WriteLi ne("Path is " + GetXPath(deepes tElement));
}
XPathNavigator deepestNode = GetDeepestNode( xmlDocument);
if (deepestElement != null) {
Console.WriteLi ne("Found node of type {0}, value {1}.",
deepestNode.Nod eType, deepestNode.Val ue);
Console.WriteLi ne("Path is " + GetXPath(deepes tNode));
}
}

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

public static XPathNavigator GetDeepestNode (IXPathNavigabl e xmlInput,
string nodeTest) {
XPathNavigator xPathNavigator = xmlInput.Create Navigator();
XPathExpression xPathExpression = xPathNavigator. Compile("//" +
nodeTest);
xPathExpression .AddSort("count (ancestor::node ())",
XmlSortOrder.De scending, XmlCaseOrder.No ne, "", XmlDataType.Num ber);
XPathNodeIterat or nodeIterator =
xPathNavigator. Select(xPathExp ression);
if (nodeIterator.M oveNext()) {
return nodeIterator.Cu rrent;
}
else {
return null;
}
}

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

public static string GetXPath (XPathNavigator navigator, string
currentPath) {
string name = "";
switch (navigator.Node Type) {
case XPathNodeType.R oot:
return "/" + currentPath;
case XPathNodeType.E lement:
name = navigator.Name;
goto case XPathNodeType.T ext;
case XPathNodeType.C omment:
name = "comment()" ;
goto case XPathNodeType.T ext;
case XPathNodeType.P rocessingInstru ction:
name = "processing-instruction()";
goto case XPathNodeType.T ext;
case XPathNodeType.T ext:
if (name == "") {
name = "text()";
}
int position =
Convert.ToInt32 ((double)naviga tor.Evaluate("c ount(preceding-sibling::" +
name + ")")) + 1;
navigator.MoveT oParent();
return GetXPath(naviga tor, 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
6823
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 elements, attributes, ".", and "..", plus also the "" predicate format is supported - however, only one predicate per path step is supported, and expr must be a relative path. 2. Poor performance
4
21210
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 native English speaker, it's quite hard to make the problem clear. Please see the following example.
5
3306
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: not this one
9
2155
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 should work. Also the second nav.OuterXml appears to also be wrong to me. Can someone explain to me why this does not work? (This is an example from a program we have where xpath can be entered in two parts so we have to be able
3
1458
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> </Root> I would like to retreive "\Root\Customer\Name" out of it. Something like:
0
1159
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> </Root> I would like to retreive "\Root\Customer\Name" out of it. Something like:
3
4979
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 version="1.0" encoding="utf-8" ?> <thing xmlns="urn:thing-schema-v1"> <foo>foo thing</foo> <bar>bar thing</bar>
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9116
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.