Friday, May 4, 2012

vb.net and xpath example

Given the XML above, the following VB.NET code would find all of the name nodes and put up a message box with the text of each node.

Dim nodeList As XmlNodeList
nodeList = doc.DocumentElement.SelectNodes("/books/book/name")
Dim name As XmlNode
For Each name In nodeList
MsgBox(name.InnerText)
Next
You can use this code to find just the name of the first book:

Dim node As XmlNode
node = doc.DocumentElement.SelectSingleNode("/books/book/name")
MsgBox(node.InnerText)
Similar recipes work for C#:

XmlNodeList nodes = doc.DocumentElement.SelectNodes( "/books/book/name" );
foreach( XmlNode node in nodes )
{
Console.WriteLine( node.InnerText );
}
This code finds all of the name nodes and prints them to the console. Getting a single node looks like this:

XmlNode singleNode = doc.SelectSingleNode( "/books/book/name" );
Console.WriteLine( singleNode.InnerText );
In XSLT you use XPath constantly to specify nodes or template-matching criteria.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text" />
<xsl:template match="/">
<xsl:for-each select="/books/book/name">
<xsl:value-of select="."/><xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

No comments:

Post a Comment

Blog Archive