1

我目前正在使用 XPath 从使用 Java 和 XPath 的播客提要中获取一些信息。我正在尝试读取节点的属性:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:atom="http://www.w3.org/2005/Atom/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">
  <channel>
    [....]
    <itunes:image href="http://icebox.5by5.tv/images/broadcasts/14/cover.jpg" />
[...]

我想获取href<itunes:image> 中的属性值。目前,我正在使用以下代码:

private static String IMAGE_XPATH = "//channel/itunes:image/@href";
String imageUrl = xpath.compile(IMAGE_XPATH).evaluate(doc, XPathConstants.STRING).toString();

imageUrl 的结果是null。代码中发生了什么?XPath 代码或 Java 代码中是否有错误?

谢谢!:)

4

2 回答 2

4

禁用命名空间警告:

DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
xmlFact.setNamespaceAware(false);

您的 xpath 表达式现在应该如下所示:

"//channel/image/@href"

如果您需要将其用作命名空间感知,只需实现您自己的NameSpaceContext,应该如下所示:

NamespaceContext ctx = new ItunesNamespaceContext();

XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
xpath.setNamespaceContext(ctx);
String IMAGE_XPATH = "//channel/itunes:image/@href";
String imageUrl = path.compile(IMAGE_XPATH).evaluate(doc,XPathConstants.STRING).toString();

编辑:这是证明我的观点的测试代码:

String a ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:sy=\"http://purl.org/rss/1.0/modules/syndication/\" xmlns:admin=\"http://webns.net/mvcb/\" xmlns:atom=\"http://www.w3.org/2005/Atom/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\" xmlns:itunes=\"http://www.itunes.com/dtds/podcast-1.0.dtd\" version=\"2.0\"><channel><itunes:image href=\"http://icebox.5by5.tv/images/broadcasts/14/cover.jpg\" /></channel></rss>";
DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
xmlFact.setNamespaceAware(false);
DocumentBuilder builder = xmlFact.newDocumentBuilder();
XPathFactory xpathFactory = XPathFactory.newInstance();
String expr = "//channel/image/@href";
XPath xpath = xpathFactory.newXPath();
Document doc = builder.parse(new InputSource(new StringReader(a)));
String imageUrl = (String) xpath.compile(expr).evaluate(doc ,XPathConstants.STRING);
System.out.println(imageUrl);

输出是:

http://icebox.5by5.tv/images/broadcasts/14/cover.jpg
于 2012-06-26T22:07:13.293 回答
0

XPath 应该包含根元素,例如 rss/channel/itunes:image/@href。

或者,您可以使用 // 开始 xpath,以便在所有级别中搜索 xpath (//channel/itunes:image/@href),但如果根始终相同,则使用第一个选项更有效.

于 2012-06-26T15:54:05.820 回答