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

该代码示例展示了如何在Java中利用XPath和DOM操作将具有特定image_id属性的'pose'元素移动到XML文档中所有'pose'元素的第一个位置。通过查找目标元素,克隆它,然后在第一个'pose'元素前插入克隆节点,从而实现元素的移动,最后删除原始元素。
摘要由CSDN通过智能技术生成

使用

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元素.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值