如何通过命名空间获取具有相同标记名称的所有元素?

时间:2016-04-01 18:40:28

标签: java xml xpath

我需要获取所有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);

建议?

1 个答案:

答案 0 :(得分:1)

首先需要设置factory.setNamespaceAware(true)。然后getElementsByTagNameNS应该有效。