在java中重新排序nodelist

时间:2013-06-12 21:14:53

标签: java live nodelist

我正在尝试重新排序由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();


  } 

}

0 个答案:

没有答案