在java中创建XML树并将其转换为json对象

时间:2014-10-15 18:17:11

标签: java xml json

我试图创建树也能够转换为json。但只有一个xpath。当我尝试实现多个xpath时,我无法获得所需的输出。我在这里分享我的实现

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) {
                        //node = (Node) nodes;   // getting class cast exception
                        continue;                

                    } else {
                        node = node
                                .appendChild(dom.createElement(xpath.get(k)));
                    }
                }
                node.appendChild(dom.createTextNode(element));
                // System.out.println(nodes);
                System.out.println(dom);
                System.out.println(node);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;

    }

我得到的输出是

<?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>

正如你可以看到节点重复,我不知道我错在哪里。我想要的输出应该是

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Tree>
    <Product>
        <Organization>
                <RegisteredDetail>
                            product2
                            <something>product1</something>
                </RegisteredDetail>
        </Organization>
    </Product>
</Tree>

在某种程度上,我在第二次迭代时犯了一些错误。

0 个答案:

没有答案