繁体   English   中英

如何使用XML Java DOM重新排序节点

[英]How to reorder a node using XML Java DOM

这是我的,

<animation_state>
<state>run</state>
<animation_sequence>
<pose duration="10" image_id="1"/>
<pose duration="10" image_id="2"/>
<pose duration="10" image_id="3"/>
</animation_sequence>

我想让用户能够上下移动某个图像,但是,因为它们以XML格式存储,这意味着我必须更改图像ID。 如果假设用户想要image_id = 3,成为序列中的第一个,或者在中间,或者根据他的需要在哪里,我该如何操作XML? 我正在使用DOM。

如果用户想要第3个图像,那么这就是我的XML应该出现的方式:

<animation_state>
<state>run</state>
<animation_sequence>
<pose duration="10" image_id="3"/>
<pose duration="10" image_id="1"/>
<pose duration="10" image_id="2"/>
</animation_sequence>

我的尝试:

Document dom = parser.getDocument();
for (int i = 0; i < dom.getElementsByTagName("animation_state").getLength(); i++) 
{
    if (dom.getElementsByTagName("animation_state").item(i).getChildNodes().item(0).getTextContent().equalsIgnoreCase(target)) {
        posVal = i;
    }
}
NodeList list = dom.getElementsByTagName("animation_sequence").item(posVal).getChildNodes();

for(int b=0; b<list.getLength(); b++)
{
    if(list.item(b).getAttributes().item(1).getNodeValue().equalsIgnoreCase(PoseSelectionListener.imageIDOfSelectedPose))
    {
        Node toBeMoved = list.item(b);
        dom.getElementsByTagName("animation_sequence").item(posVal).appendChild(toBeMoved);
        System.out.println(toBeMoved.getAttributes().item(0).getNodeName());
    }
}

使用Node.insertBefore和/或Node.appendChild只需找到要移动的节点并找到它应该移动的位置,然后在该节点之前插入该节点。

您可能更容易创建要移动的节点的副本 ,将其插入正确的位置,然后删除旧节点

请参阅以下示例代码:

public class SO13782330 {
    /** Move the image whose imageId is given at first position in sequence */
    public static void moveImageFirst(Document doc, int imageId) throws Exception {
        XPath xpath = XPathFactory.newInstance().newXPath();
        // get the image to move
        XPathExpression poseXPath = xpath.compile("//pose[@image_id='" + imageId + "']");
        Node pose = (Node)poseXPath.evaluate(doc, XPathConstants.NODE);
        // get the first image
        XPathExpression firstPoseXPath = xpath.compile("//pose[position() = 1]");
        Node firstPose = (Node)firstPoseXPath.evaluate(doc, XPathConstants.NODE);
        // copy the image to be moved
        Node poseCopy = pose.cloneNode(true);
        // insert it before the first one
        Node sequence = firstPose.getParentNode();
        sequence.insertBefore(poseCopy, firstPose);
        // delete the old one
        sequence.removeChild(pose);
    }

    /** Print the document on stdout */
    public static void showDocument(Document doc) throws Exception {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter sw = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(sw));
        System.out.println(sw.getBuffer().toString());
    }

    public static void main(String... args) throws Exception {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader("<animation_state>\n" +
                "<state>run</state>\n" +
                "<animation_sequence>\n" +
                "<pose duration=\"10\" image_id=\"1\"/>\n" +
                "<pose duration=\"10\" image_id=\"2\"/>\n" +
                "<pose duration=\"10\" image_id=\"3\"/>\n" +
                "</animation_sequence>\n" +
                "</animation_state>")));
        moveImageFirst(doc, 3);
        showDocument(doc);
    }
}

它将在第一个之前移动具有image_id属性等于3pose元素。

您不需要复制/克隆节点。

只需执行以下操作

public void addNodeAfter(Node newNode, Node refChild) {
    Node parent = refChild.getParent();
    parent.insertBefore(newNode, refChild);
    refChild = parent.remove(refChild);
    parent.insertBefore(refChild, newNode); 
}

可能是比克隆更好的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM