Retrieving XML path text values

A

Abraham Khalil

Trying to write a function to get all values from a XML path without using a
third party XPath libraries

Using jdk1.4 and wondering if it supports XPaths?
If so would prefer that as a solution instead of writing a recursive one myself

Thanks

An example of a start that I'am trying below


public static String[] getValue(Document doc, String path) throws Exception {
String[] nodeNames = path.split("[\\/]");

for (int i = 0 ; i < nodeNames.length ; i++) {
String nodeName = nodeNames;
NodeList elements = doc.getElementsByTagName(nodeName);
}
}
 
A

Adam Jenkins

Abraham said:
Trying to write a function to get all values from a XML path without using a
third party XPath libraries

Using jdk1.4 and wondering if it supports XPaths?
If so would prefer that as a solution instead of writing a recursive one myself

Unfortunately there is no standard way to apply an XPath expression to
an org.w3c.dom.Node. However, the implementation of javax.xml.* that
ships with Sun's JDK is Xalan, which does include nice XPath support.
So if you're using Sun's JDK, you can write code like

import org.apache.xpath.XPathAPI;
import org.w3c.dom.*;

// find the first node matching an XPath expression in
// the subtree starting at "node"
Node getNode(Node node, String xpathExpr) throws Exception {
return XPathAPI.selectSingleNode(node, xpathExpr);
}

// get the string value of an XPath expression
String getNodeValue(Node node, String xpathExpr) throws Exception {
return XPathAPI.eval(node, xpathExpr).str();
}

Even if you are using a JDK that doesn't come with Xalan, you can get it
free from http://xml.apache.org. The license allows it to be used in
commercial products, so I see no reason to write your own XPath
interpreter, except for fun.
An example of a start that I'am trying below


public static String[] getValue(Document doc, String path) throws Exception {
String[] nodeNames = path.split("[\\/]");

for (int i = 0 ; i < nodeNames.length ; i++) {
String nodeName = nodeNames;
NodeList elements = doc.getElementsByTagName(nodeName);
}
}


That's a start, but I bet pretty soon you'll want to evaluate more
complex XPath expression, and next thing you know you'll be implementing
your own XPath interpreter. Unless you're doing it for fun, I don't see
the point since Xalan works well already.

Adam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,010
Latest member
MerrillEic

Latest Threads

Top