我需要获取所有url
元素的<media:content/>
属性列表:
这是我的XML:
<rss version='2.0' xmlns:media='http://search.yahoo.com/mrss/'>
<channel>
<item>
<media:group>
<media:content url='https://valor'/>
</media:group>
</item>
<item>
<media:group>
<media:content url='https://valor'/>
</media:group>
</item>
</channel>
</rss>
我试过了,但contents.getLength()
返回0个元素
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
NodeList contents = doc.getElementsByTagNameNS("http://search.yahoo.com/mrss/", "content");
此外,我尝试使用XPath ...但同样,contents.getLength()
返回0个元素
XPathFactory factory2 = XPathFactory.newInstance();
XPath xpath = factory2.newXPath();
// XPathExpression expr = xpath.compile("//content");
XPathExpression expr = xpath.compile("//*[name()='content']");
NodeList contents = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
建议?
答案 0 :(得分:1)
首先需要设置factory.setNamespaceAware(true)
。然后getElementsByTagNameNS
应该有效。