Last active
August 29, 2015 14:25
-
-
Save bootstraponline/9d17040deb5b08dde28e to your computer and use it in GitHub Desktop.
Client Side Xpath
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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