I'm trying to read in an XML using DOM in Java
<?xml version="1.0"?>
<record>
<user>
<name>Leo</name>
<email>****@****.com</email>
<food-list>
<food>Hamburgers</food>
<food>Fish</food>
</food-list>
</user>
</record>
My current solution is
for (int userNumber = 0; userNumber < masterList.getLength(); userNumber++) {
Node singleUserEntry = masterList.item(userNumber);
if (singleUserEntry.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element userEntryElement = (org.w3c.dom.Element) singleUserEntry;
System.out.println("name : " + getTagValue("name", userEntryElement));
System.out.println("email : " +getTagValue("email", userEntryElement));
NodeList foodList = userEntryElement.getElementsByTagName("food-list").item(0).getChildNodes();
for(int i = 0; i < foodList.getLength(); i++){
Node foodNode = foodList.item(i);
System.out.println("food : " + foodNode.getNodeValue());
}
private static String getTagValue(String sTag, org.w3c.dom.Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
And the output now is
name : Leo
email : ******@*****.com
food :
food : null
food :
food : null
food :
Which quite confuses me. Could you tell me where I'm wrong? The number of food tags is not pre-defined.
((Node) foodNode.getChildNodes().item(0)).getNodeValue()
Note that, as you can clearly see, dealing with the DOM API in Java is pretty painful. Have you looked at JDOM or dom4j?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With