I tried to create a tree also able to convert to json. But only for one xpath. When I tried to implement multiple xpath, I could not get the desired result. Here I share my implementation
private static Document addElemtbypath(List<String> pathList1, List<String> elementList) { Document doc = null; try { DocumentBuilderFactory docfactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docfactory.newDocumentBuilder(); doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Tree"); doc.appendChild(rootElement); for (int i = 0; i < pathList1.size(); i++) { String pathList = pathList1.get(i); String element = elementList.get(i); List<String> xpath = new LinkedList<>(); String[] parts = pathList.split("/"); for (int j = 0; j < parts.length; j++) { xpath.add(parts[j]); } System.out.println(xpath); Node node = doc.getDocumentElement(); Document dom = node.getOwnerDocument(); System.out.println(node); for (int k = 0; k < xpath.size(); k++) { XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.evaluate(xpath.get(k), doc.getDocumentElement(), XPathConstants.NODESET); if (nodes.getLength() != 0) {
and the result is
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <Tree> <Product> <Organization> <RegisteredDetail> <something>product1</something> </RegisteredDetail> </Organization> </Product> <Organization> <RegisteredDetail>product2</RegisteredDetail> </Organization> </Tree>
As you can see the nodes are repeating, I donβt know where I was wrong. My desired result should look like
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <Tree> <Product> <Organization> <RegisteredDetail> product2 <something>product1</something> </RegisteredDetail> </Organization> </Product> </Tree>
One way or another, I am mistaken in repeating the second time.
java json xml
Sudip7 Oct 15 '14 at 18:17 2014-10-15 18:17
source share