使用
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("\n" +
"run\n" +
"\n" +
"\n" +
"\n" +
"\n" +
"\n" +
"")));
moveImageFirst(doc, 3);
showDocument(doc);
}
}
它将在第一个之前移动具有image_id属性等于3的pose元素.