How to parse XML with multiple values using DOM in JAVA



I'm trying to parse the XML with follwing structure



<?xml version="1.0" encoding="UTF-8" ?>
<countryInformationFilter>
<service>
<name>Cash Management</name>
<serviceCategory>
<name>Cash Pooling</name>
<SupportedCountries>Germany</SupportedCountries>
<SupportedCountries>Italy</SupportedCountries>
</serviceCategory>
</service>
<service>
<name>eBanking</name>
<serviceCategory>
<name>Application</name>
<SupportedCountries>Bosnia</SupportedCountries>
<SupportedCountries>Brazil</SupportedCountries>
<SupportedCountries>Bulgaria</SupportedCountries>
<SupportedCountries>China</SupportedCountries>
</serviceCategory>
<serviceCategory>
<name>Services</name>
<SupportedCountries>Czech Republic</SupportedCountries>
<SupportedCountries>Hungary</SupportedCountries>
<SupportedCountries>Poland</SupportedCountries>
</serviceCategory>
<serviceCategory>
<name>Forms</name>
<SupportedCountries>Romania</SupportedCountries>
<SupportedCountries>Russia</SupportedCountries>
<SupportedCountries>Serbia</SupportedCountries>
<SupportedCountries>Singapore</SupportedCountries>
</serviceCategory>
</service>
</countryInformationFilter>


using the following JAVA code



DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName(XMLKeyIdentifiers.SERVICE);

for (int index = 0; index < nList.getLength(); index++) {
Node nNode = nList.item(index);

if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;

System.out.println("NAME : " + eElement.getElementsByTagName("name").item(0).getTextContent());
NodeList nListCategory = doc.getElementsByTagName(XMLKeyIdentifiers.SERVICE_CATEGORY);
for (int indexCategory = 0; indexCategory < nListCategory.getLength(); indexCategory++) {
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElementCategory = (Element) nNode;

System.out.println("-------------");
System.out.println("Name : " + eElementCategory.getElementsByTagName("name").item(0).getTextContent());
System.out.println("SupportedCountries : " + eElementCategory.getElementsByTagName("SupportedCountries").item(0).getTextContent());
System.out.println("-------------");
}
}
}
}


Please help me to solve this riddle.


Suggestions will be appreciated.


No comments:

Post a Comment