Reputation: 42173
I am using the DOM
parser in Java
and am trying to return the child node elements. Here is what my XML looks like:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<group name="Recently Added">
<item>
<asset>138682</asset>
<date>Mar 05, 2015</date>
<artist>
<![CDATA[Marlin G. Meharry, D.D.S]]>
</artist>
<album>
<![CDATA[Career Day - Marlin G. Meharry, D.D.S]]>
</album>
<url>
<![CDATA[http://web2.puc.edu/Departments/Media_Services/file/2015/CarDayMarlinGMeharryDDS.mp3]]>
</url>
<length>
<![CDATA[36:48]]>
</length>
</item>
<item>
<asset>140705</asset>
<date>Jan 01, 2000</date>
<artist>
<![CDATA[John Nunes]]>
</artist>
<album>
<![CDATA[Educator of the Year]]>
</album>
<url>
<![CDATA[http://web2.puc.edu/Departments/Media_Services/file/2015/2015-4-2LloydBest.mp3]]>
</url>
<length>
<![CDATA[40:46]]>
</length>
</item>
</group>
<group name="Heubach Lectureship Series">
<item>
<asset>48041</asset>
<date>Mar 07, 2009</date>
<artist>
<![CDATA[Barry C. Black, United States Senate Chaplain]]>
</artist>
<album>
<![CDATA[Heubach Lecture]]>
</album>
<url>
<![CDATA[http://web2.puc.edu/Departments/Media_Services/file/2009/HeubachLecture030709.mp3]]>
</url>
<length>
<![CDATA[1:12:57]]>
</length>
</item>
</group>
</body>
So, below my root element I have group nodes which are like arrays, as they hold item nodes. I need to get at the item nodes to get their data. Here is what I have come up with so far, but am still unsure where to go next:
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(in);
NodeList categoryList = doc.getElementsByTagName("group");
for (int categoryNo=0; categoryNo<categoryList.getLength(); categoryNo++) {
//Element categoryNode = (Element)categoryList.item(categoryNo);
Node node = categoryList.item(categoryNo);
NodeList childNodes = categoryList.item(categoryNo).getChildNodes();
for (int childNo = 0; childNo < childNodes.getLength(); childNo++) {
Node childNode = childNodes.item(childNo);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) childNode;
Log.d(elem.getNodeValue(), "Zed");
}
}
}
Any hints as to how to get those item nodes such as asset, artist, album, etc?
Upvotes: 1
Views: 6124
Reputation: 72884
Since elem
corresponds to the item
element in the XML, you can retrieve a child element using Element#getElementsByTagName(String elementName)
, similar to what you do to get the group
elements. Then you can retrieve the content of the element using Node#getTextContent()
. For instance:
Element elem = (Element) childNode;
NodeList assetNodes = elem.getElementsByTagName("asset");
if(assetNodes.getLength() > 0) {
// get the text content of the first node
String asset = assetNodes.item(0).getTextContent();
...
}
Upvotes: 2