Skip to content

Instantly share code, notes, and snippets.

@bootstraponline
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bootstraponline/9d17040deb5b08dde28e to your computer and use it in GitHub Desktop.
Save bootstraponline/9d17040deb5b08dde28e to your computer and use it in GitHub Desktop.
Client Side Xpath
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
public class PageSource {
private final XPath xpath = XPathFactory.newInstance().newXPath();
private String pageSource;
public PageSource(String pageSource) {
this.pageSource = pageSource;
}
public String getTextFromNode(String xpathExpression) {
xpathExpression = Localizer.localize(xpathExpression);
try {
return (String) this.xpath.evaluate(xpathExpression, new InputSource(new StringReader(pageSource.replaceAll("\\r|\\n", ""))), XPathConstants.STRING);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
public Node getNode(String xpathExpression){
xpathExpression = Localizer.localize(xpathExpression);
try {
return (Node) this.xpath.evaluate(xpathExpression, new InputSource(new StringReader(pageSource)), XPathConstants.NODE);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
public NodeList getNodes(String xpathExpression){
xpathExpression = Localizer.localize(xpathExpression);
try {
return (NodeList) this.xpath.evaluate(xpathExpression, new InputSource(new StringReader(pageSource)), XPathConstants.NODESET);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
@Override
public String toString() {
return pageSource;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment