The reason you're getting only one <producttype>
(Nokia) instead of the complete list because you're looping over the length of <ProductType>
nodes thinking you're looping over the <producttype>
ones.
So, you need another inner loop to cover all the child product type nodes like
for(int ptCnt=0; ptCnt < productTypeNL.getLength(); ptCnt++) {
Node productTypeNode = productTypeNL.item(ptCnt);
if(productTypeNode.hasChildNodes()){
NodeList childProductTypeNL = productTypeNode.getChildNodes();
System.out.print("Product Types are: ");
for (int cptCnt=0; cptCnt < childProductTypeNL.getLength(); cptCnt++) {
productTypeBean = new ProductType();
productTypeBean.setmProductType (
childProductTypeNL.item(cptCnt).getTextContent());
System.out.print(productTypeBean.getmProductType() + ", ");
ProductTypeAL.add(productTypeBean);
}
}
productBean.setmProductTypes(ProductTypeAL);
}
I've directly used the Node.getChildNodes()
and Node.getTextContexnt()
methods, instead of type casting to Element
first and using its methods or the XMLfunctions
utility class.
I also recommend using different names for child nodes instead of relying on using a different case to avoid such problems in future. A simple way to avoid name collision (when you're not able to come up with a different name) is to simply use a plural like <ProductTypes>
for the parent tag.
However, a better approach when you need to parse deep within a DOM tree is to use an XPath
to directly get the list of nodes you're interested in. I'm not entirely sure what the program does but just to give you an example an XPath
like
String xpath = "//product[@name=\"viki\"]/ProductType/producttype";
would give you the NodeList
for <producttype>
nodes directly.