Я пытаюсь разобрать элемент dom.
Элемент элемента:
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<id>http://X/feed2</id>
<title>Sample Feed</title>
<entry>
<id>http://X/feed2/104</id>
<title>New Title</title>
</entry>
</feed>
Я пытаюсь получить следующую запись:
<entry>
<id>http://top.cs.vt.edu/libx2/vsony7@vt.edu/feed2/104</id>
<title>New Title</title>
</entry>
Япарсинг xml с помощью xpath:
"/ atom: feed / atom: entry [atom: id = \" http://X/feed2/104\"]"
Но я получаю исключение, когда пытаюсь проанализировать Dom Element.Может кто-нибудь предложить простой подход для достижения этого в Java?
Пожалуйста, смотрите мой полный код:
public static parseXml() {
String externalEntryIdUrl = "http://theta.cs.vt.edu/~rupen/thirtylibapps/137";
String externalFeedUrl = StringUtils.substringBeforeLast(externalEntryIdUrl, "/");
try {
URL url = new URL(externalFeedUrl);
InputStream externalXml = new BufferedInputStream(url.openStream());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(externalXml);
Element externalFeed = doc.getDocumentElement();
String atomNameSpace = "xmlns:atom=\"http://www.w3.org/2005/Atom\"";
String entryIdPath = String.format("//%s:entry[%s:id=%s]", atomNameSpace, atomNameSpace, externalEntryIdUrl);
Element externalEntry = (Element) XPathSupport.evalNode(entryIdPath, externalFeed);
} catch (Exception ex) {
// Throw exception
}
}
static synchronized Node evalNode(String xpathExpr, Node node) {
NodeList result = evalNodeSet(xpathExpr, node);
if (result.getLength() > 1)
throw new Error ("More than one node for:" + xpathExpr);
else if (result.getLength() == 1)
return result.item(0);
else
return null;
}
static synchronized NodeList evalNodeSet(String xpathExpr, Node node) {
try {
static XPath xpath = factory.newXPath();
xpath.setNamespaceContext(context);
static NamespaceContext context = new NamespaceContext() {
private Map<String, String> prefix2URI = new HashMap<String, String>();
{
prefix2URI.put("libx", "http://libx.org/xml/libx2");
prefix2URI.put("atom", "http://www.w3.org/2005/Atom");
}
};
XPathExpression expr = xpath.compile(xpathExpr);
Object result = expr.evaluate(node, XPathConstants.NODESET);
return (NodeList)result;
} catch (XPathExpressionException xpee) {
throw new Error ("An xpath expression exception: " + xpee);
}
}
SEVERE: >> java.lang.Error: Исключение выражения xpath: javax.xml.xpath.XPathExpressionException