0

我正在尝试重新排序由 xpath 表达式生成的节点列表。我已经设法通过将列表中的所有节点一一复制到新文档(以任何顺序)并使用 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();


  } 

}

4

0 回答 0