January 25, 2010

Intro to XPath

Helpful XPath syntax reference from W3

Sample code based loosely on this Java2S example:

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLParserAlpha
{
private static final String SOURCE = "C:/someFolder/xmlFile.xml";
private static final String EXPR = "*";

public static void main(String[] args)
{
XPath xpath = XPathFactory.newInstance().newXPath();
String xpathExpression = EXPR;
InputSource inputSource = new InputSource(SOURCE);

NodeList nodes = null;
int j = -1;
try
{
nodes = (NodeList) xpath.evaluate(xpathExpression, inputSource, XPathConstants.NODESET);
// NODESET maps to interface org.w3c.dom.NodeList
j = nodes.getLength();

for (int i = 0; i < j; i++) { System.out.println(nodes.item(i).getTextContent()); } } catch (XPathExpressionException e) { e.printStackTrace(); } } }


Other values of EXPR and what they're good for:
/Report/PublicationMetadata/DescriptiveMetadata/Title/@* - All attribute values of the title element (but not the attribute names)

TODO: FINISH POST

No comments:

Post a Comment