Get the name and value of all child nodes of a root node in the xml
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.jxpath.Pointer;
import org.jdom.Element;
import org.w3c.dom.Document;
/**
Document - The Document object for the xml
Pointer - The JXPathContext pointers for the root node
loop - The number of occurances of the root node in the xml
**/
Map<String, Object> getCompositeData(Document document, Pointer pointer, int loop) {
Map<String, Object> bean = new HashMap<String, Object>();
String compositeXpath = pointer.asPath();
try {
XPathFactory factory=XPathFactory.newInstance();
XPath xPath=factory.newXPath();
Element node = (Element) (xPath.evaluate(compositeXpath,
document, XPathConstants.NODE));
List childNodeLists = node.getChildren();
bean.putAll(getNameValue(childNodeLists,loop));
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return bean;
}
Map<String, Object> getNameValue(List childrenNodeLists, int loop) {
Map<String, Object> bean = new HashMap<String, Object>();
for (Object compNode : childrenNodeLists) {
Element node = (Element) compNode;
List childNodes = node.getChildren();
if (childNodes.size() > 0) {
bean.putAll(getNameValue(childNodes, loop));
} else {
bean.put(new SimpleBean(loop == 0 ? node.getName() : node.getName() + "_" + loop, node.getValue()));
}
}
return bean;
}