Java tutorial
//package com.java2s; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { public static void insertBefore(Node source, Node target) { target.getParentNode().insertBefore(source, target); } public static void insertBefore(Node node, String sourceExpress, String targetExpress) { NodeList sources = selectNodes(node, sourceExpress); Node target = selectSingleNode(node, targetExpress); if (sources != null && target != null) { for (int i = 0; i < sources.getLength(); i++) { insertBefore(sources.item(i), target); } } } public static NodeList selectNodes(Node node, String express) { NodeList result = null; XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); try { result = (NodeList) xpath.evaluate(express, node, XPathConstants.NODESET); } catch (XPathExpressionException e) { e.printStackTrace(); } return result; } public static Node selectSingleNode(Node node, String express) { Node result = null; XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); try { result = (Node) xpath.evaluate(express, node, XPathConstants.NODE); } catch (XPathExpressionException e) { e.printStackTrace(); } return result; } }