Java XML插入父节点

时间:2016-06-29 12:09:55

标签: java xml

我有以下xml

<Root>
    <Page>
        <Object ref="a"></Object>
        <Object ref="b"></Object>
    </Page>
</Root>

我想转换成

<Root>
    <Page>
        <ObjectGroup ref="a">
            <Object ref="a"/>
        </ObjectGroup>
        <ObjectGroup ref="b">
            <Object ref="b"/>
        </ObjectGroup>
    </Page>
</Root>

基本上我想介绍一个新的父节点。我使用了以下方式,但它引入了更多的父母

 private static void loadRoots(String xMLPath) {
        Document doc = Migrate.initTreeOpFromString(xMLPath);
        Element rootElement = doc.getDocumentElement();
        loadPage(rootElement);
        Migrate.finishTreeOp(doc, "D:\\a.xml");
    }

    private static void loadPage(Element root) {
        NodeList pageNodes = root.getChildNodes();
        for (int j = 0; j < pageNodes.getLength(); j++) {
            Node pageNode = pageNodes.item(j);
            if (pageNode.getNodeType() == Node.ELEMENT_NODE) {
                loadObject((Element) pageNode);
            }
        }
    }

    private static void loadObject(Element pageNode) {
        NodeList objectNodes = pageNode.getChildNodes();
        for (int j = 0; j < objectNodes.getLength(); j++) {
            Node objectNode = objectNodes.item(j);
            if (objectNode.getNodeType() == Node.ELEMENT_NODE) {
                Element objGroup = pageNode.getOwnerDocument().createElement("ObjectGroup");
                String ref = objectNode.getAttributes().getNamedItem("ref").getTextContent();
                objGroup.setAttribute("ref", ref);
                pageNode.removeChild(objectNode);
                objGroup.appendChild(objectNode);
                pageNode.appendChild(objGroup);
            }
        }
    }

但是这个的输出是

<Root>
    <Page>
        <ObjectGroup ref="b">
            <Object ref="b"/>
        </ObjectGroup>
        <ObjectGroup ref="a">
            <ObjectGroup ref="a">
                <ObjectGroup ref="a">
                    <Object ref="a"/>
                </ObjectGroup>
            </ObjectGroup>
        </ObjectGroup>
    </Page>
</Root>

这不是我想要的。我该如何解决这个问题

1 个答案:

答案 0 :(得分:0)

这是我的错。我应该使用insertBefore。这就是诀窍

private static void loadObject(Element pageNode) {
        NodeList objectNodes = pageNode.getChildNodes();
        for (int j = 0; j < objectNodes.getLength(); j++) {
            Node objectNode = objectNodes.item(j);
            if (objectNode.getNodeType() == Node.ELEMENT_NODE) {
                Element objGroup = pageNode.getOwnerDocument().createElement("ObjectGroup");
                String ref = objectNode.getAttributes().getNamedItem("ref").getTextContent();
                objGroup.setAttribute("ref", ref);
                pageNode.insertBefore(objGroup, objectNode);
                objGroup.appendChild(objectNode);
            }
        }
    }