Skip to content

Instantly share code, notes, and snippets.

@tag1216
Created December 17, 2014 06:06
Show Gist options
  • Save tag1216/2a2e7ce56dd3d72d19f1 to your computer and use it in GitHub Desktop.
Save tag1216/2a2e7ce56dd3d72d19f1 to your computer and use it in GitHub Desktop.
DomツリーからXPathでノードを選択するクラス。
/**
* DomツリーからXPathでノードを選択するクラス。
*/
public class DomNode {
private static XPathFactory xpathFactory = XPathFactory.newInstance();
private Optional<Node> node;
public DomNode(Node node) {
this.node = Optional.of(node);
}
public Optional<Node> get() {
return node;
}
public String name() {
return node.map(x -> x.getNodeName()).orElse(null);
}
public String attr(String name) {
return node.map(x -> x.getAttributes().getNamedItem(name))
.map(x -> x.getNodeValue())
.orElse(null);
}
public String text() {
return node.map(x -> x.getTextContent()).orElse(null);
}
public DomNode selectNode(String path) {
Objects.requireNonNull(path);
try {
return new DomNode((Node) xpathFactory.newXPath().compile(path).evaluate(node.get(), XPathConstants.NODE));
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
public List<DomNode> selectNodeSet(String path) {
Objects.requireNonNull(path);
try {
NodeList nodeList = (NodeList) xpathFactory.newXPath().compile(path).evaluate(node.get(), XPathConstants.NODESET);
List<DomNode> list = new ArrayList<>();
for (int i = 0; i < nodeList.getLength(); i++) {
list.add(new DomNode(nodeList.item(i)));
}
return list;
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
public Optional<String> selectText(String path) {
Objects.requireNonNull(path);
try {
String text = (String) xpathFactory.newXPath().compile(path).evaluate(node.get(), XPathConstants.STRING);
return Optional.ofNullable(text);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment