我正在使用 COBRA HTMLParser,但没有运气解析一个特定的标签。这是来源:
<li id="eta" class="hentry">
<span class="body">
<span class="actions">
</span>
<span class="content">
</span>
<span class="meta entry">Content here
</span>
<span class="meta entry stub">Content here
<span class="shared-content">
Information by
<a class="title" data="associate" href="/associate">Associate</a>
</span>
</span>
</span>
</li>
我可以使用以下 XPath 来获取正确的信息:
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xpath.evaluate("//span[contains(@class, 'body')]", document, XPathConstants.NODESET);
int length = nodeList.getLength();
System.out.println(nodeList.getLength());
for(int i = 0; i < length; i++) {
Element element = (Element) nodeList.item(i);
NodeList n = null;
try {
n = (NodeList) xpath.evaluate("span[contains(@class, 'content')]", element, XPathConstants.NODESET);
String body = n.item(0).getTextContent();
System.out.println("Content: " + body);
} catch (Exception e) {};
try {
String date = (String) xpath.evaluate("span[contains(@class, 'meta entry')]/a/span/@data", element, XPathConstants.STRING);
System.out.println("DATA: " + date);
String source = (String) xpath.evaluate("//span[contains(@class, 'meta entry')]/span", element, XPathConstants.STRING);
System.out.println("DATA: " + source);
} catch (Exception e) {};
//This does not work at all! I've tried every combination and still can't get it to run
try {
String info = (String) xpath.evaluate("//span[@class='shared-content']/a/@data", element, XPathConstants.STRING);
System.out.println("INFO: " + info);
} catch (Exception e) {};
}
无论我尝试什么组合,最后一个表达式都不起作用。我也尝试过以下方法,但没有帮助,
String info = (String) xpath.evaluate("//span[contains(@class, 'shared-content')]/a/@data", element, XPathConstants.STRING);
String info = (String) xpath.evaluate("//span[contains(@class, 'meta entry info')]/span/a/@data", element, XPathConstants.STRING);
有什么建议么?
编辑:有一些关于 XML 非法的建议(老实说,我不确定为什么它是非法的,因为到目前为止我几乎到处都看到过)但我无法控制 XML (至少到星期一,直到我的其他朋友回来)。我正在尝试查看编写包含此信息的混搭的可行性。有什么办法可以禁用检查吗?
这是已解析的 XML:
<?xml version="1.0" encoding="UTF-8"?>
<span class="body">
<span class="content">TextContent</span>
<span class="meta entry">TextContent</span>
</span>
我猜文档没有被正确解析。