public class XmlResolver {
private Document document;
public XmlResolver(String xml) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
document = builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
}
public List<String> searchCdataNodeByXPath(String xPathExpr) {
List<String> nodeStrList = new ArrayList<String>();
if (document != null) {
XPath xPath = XPathFactory.newInstance().newXPath();
try {
XPathExpression expr = xPath.compile(xPathExpr);
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
if (nodes != null) {
for (int i = 0;i < nodes.getLength();i++) {
Node node = nodes.item(i);
if (node != null) {
nodeStrList.add(node.getTextContent());
}
}
return nodeStrList;
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
return nodeStrList;
}
public List<Node> searchNodeByXPath(String xPathExpr) {
List<Node> nodeList = new ArrayList<Node>();
if (document != null) {
XPath xPath = XPathFactory.newInstance().newXPath();
try {
XPathExpression expr = xPath.compile(xPathExpr);
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
if (nodes != null) {
for (int i = 0;i < nodes.getLength();i++) {
nodeList.add(nodes.item(i));
}
return nodeList;
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
return nodeList;
}
public Node searchFirstNodeByXPath(String xPathExpr) {
List<Node> nodeList = searchNodeByXPath(xPathExpr);
return nodeList.isEmpty() ? null : nodeList.get(0);
}
public String getTextValue(String xPath) {
Node node = this.searchFirstNodeByXPath(xPath);
if (node != null) {
return node.getTextContent();
}
return null;
}
public String getAttrValue(String xPath, String attrName) {
Node node = this.searchFirstNodeByXPath(xPath);
if (node == null) {
return null;
}
Node attr = node.getAttributes().getNamedItem(attrName);
if (attr == null) {
return null;
}
return attr.getTextContent();
}
}