xpath 式によって生成されたノードリストを並べ替えようとしています。リスト内のすべてのノードを 1 つずつ (任意の順序で) 新しいドキュメントにコピーし、getChildNodes メソッドを使用してそれをノード リストとして返すことで、これを行うことができました。ただし、新しいリストのノードが元のノードの構造を保持するようにしたいので、たとえば、新しいノード リストのノードで getParentNodes() を実行すると、元の xml から親ノードが取得されます。
これは、私がやろうとしていることを一般的に示すコードです。
import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
public class Test {
public static void main(String args[]) throws SAXException, IOException, XPathExpressionException, ParserConfigurationException {
String xmlStr="";
String xpathStr="";
//run standard xpath expression that returns a nodelist
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(xmlStr);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr= xpath.compile(xpathStr);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
/*i need to reorder the node list so i created a secondary doc,
* and copied the nodes there one by one in the required order*/
//create second doc
DocumentBuilderFactory factory1 = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1 = factory1.newDocumentBuilder();
Document nodeListDoc = builder1.newDocument();
//create root element for the new doc
Element root = (Element) nodeListDoc.createElement("rootElement");
for (int i = 0; i < nodes.getLength(); i++) {
//import node to new doc
Node newNode=nodeListDoc.importNode(nodes.item(i),true);
//insert node into tree
root.appendChild(newNode);
//original node shows the correct parent from the xml
System.out.println("original: "+nodes.item(i).getParentNode());
//new node shows root/null as parent
System.out.println("new: "+newNode.getParentNode());
}
//save as new nodelist
NodeList nodeListOrdered= root.getChildNodes();
}
}