rnrneverdies
rnrneverdies

Reputation: 15637

How to obtain all the elements with the same tag name by namespace?

I need to obtain the list of url attribute of all <media:content/> elements:

This is my 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>

I tried this, but contents.getLength() returns 0 elements

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(inputStream);
NodeList contents = doc.getElementsByTagNameNS("http://search.yahoo.com/mrss/", "content");

Also I tried to use XPath... but again, contents.getLength() returns 0 elements

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);

suggestions?

Upvotes: 0

Views: 287

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167516

You first need to set factory.setNamespaceAware(true). Then the getElementsByTagNameNS should work.

Upvotes: 1

Related Questions