I need to get the attribute url
of all the elements <media:content/>
of an XML similar to this.
<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>
This is a method I tried, but it contents.getLength()
returns zero.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
NodeList contents = doc.getElementsByTagNameNS("http://search.yahoo.com/mrss/", "content");
I've tried using XPath... again it contents.getLength()
returns zero.
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);
I never get the required nodes, any suggestions?
To work with methods
..NS
, when you create the DOM you must call the methodfactory.setNamespaceAware(true);
To obtain the value of an attribute (in this case url), having one
.rss
of the form:Elements can be accessed by getting the list of nodes and accessing their values:
Or you can go directly to the element, in this case "
media:content
" and get the value of its " " attributeurl
:would get the value:
XML:
0OK30-1-0000013-66271741VisaGoldBs50007000-200011/01/201511/01/2020ASCACamacho30-1-0000013-6111122222VisaGold$us40002000200011/03/201411/01/20ASCAElTejar19
JAVA: You read XML: DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; String messageError = null; Integer RespCod = -1; String msgResp = ""; try { db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xmlresponse)); try { Document document = db.parse(is); NodeList responseCode = document .getElementsByTagName("ResponseCode"); NodeList responseMessage = document .getElementsByTagName("ResponseMessage");
You get the data: try { db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xmlresponse)); try { Document document = db.parse(is);
//ALL Here you iterate where you want to output } } catch (SAXException e) { e.printStackTrace(); if (logger.isDebugEnabled()) logger.logDebug(messageError); return null; } catch (IOException e) { e.printStackTrace(); if (logger.isDebugEnabled()) logger.logDebug(messageError); return null; } } catch (ParserConfigurationException e1) { e1.printStackTrace(); if (logger.isDebugEnabled()) logger.logDebug(messageError); return null; }
I hope it helps you slds...