Skip to content

Instantly share code, notes, and snippets.

@pgtwitter
Last active October 21, 2015 19:17
Show Gist options
  • Save pgtwitter/77f27f38863c741890c6 to your computer and use it in GitHub Desktop.
Save pgtwitter/77f27f38863c741890c6 to your computer and use it in GitHub Desktop.
XPath Sample
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XPathSample {
public static void main(String[] args) throws Exception {
String xmlString = createXMLString();
Document document = documentWithXMLString(xmlString);
String xpathString = "//company/url/text()";
NodeList nlist = nodeWithXPath(xpathString, document);
for (int i = 0; i < nlist.getLength(); i++) {
System.out.println("--- " + i + " ---");
System.out.println(nlist.item(i).getNodeValue());
}
}
public static Document documentWithXMLString(String xmlString)
throws SAXException, IOException, ParserConfigurationException {
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlString));
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
return doc;
}
public static NodeList nodeWithXPath(String xpathString, Document document) throws XPathExpressionException {
return (NodeList) XPathFactory.newInstance().newXPath().evaluate(xpathString, document, XPathConstants.NODESET);
}
public static String createXMLString() {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
sb.append("<companies>");
sb.append("<company>");
sb.append("<name>example.com</name>");
sb.append("<url>http://www.example.com/</url>");
sb.append("</company>");
sb.append("<company>");
sb.append("<name>example.jp</name>");
sb.append("<url>http://www.example.jp/</url>");
sb.append("</company>");
sb.append("</companies>");
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment