我想搜索xml中的特定节点或元素,并从select节点创建新的xml

时间:2016-09-27 10:21:36

标签: java xml parsing dom4j

我想从select节点创建新的Xml文件,我只使用dom4j来解析和创建新的xml文件。示例假设节点客户名称=约瑟夫是根元素TRX的子节点我想显示包含约瑟夫的整个元素并创建新文件

     enter code here
     File inputFile = new File("C:\\Users\\db2admin\\Desktop\\S4decs\\tlog01_004.xml");
     SAXReader reader = new SAXReader(true);
     reader.setValidation(false);
     reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     Document document = reader.read(inputFile);
     document.getRootElement();



     document.selectNodes("//TRX[@type]='16'").size();
     document.selectNodes("/CUSTOMER").size();




     // Pretty print the document to System.out
     OutputFormat format = OutputFormat.createPrettyPrint();
     XMLWriter writer;
     writer = new XMLWriter( System.out, format );
     writer.write( document );
  } catch (DocumentException e) {
     e.printStackTrace();
  } catch (UnsupportedEncodingException e) {         
     e.printStackTrace();
  } catch (IOException e) {
     e.printStackTrace();
  }




 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE TRANSACTIONS SYSTEM "tlog.dtd">
 <TRANSACTIONS storeid="4" sbs="780030" location="1">
 <TRX type="16" term="742" trxnum="143895" saleperson="0" supervisor_id="152332149" storeid="4" sbs="780030" opcode="153135959"  date="20160915" endtime="111000">
 </TRX>
 <TRX type="31" term="742" trxnum="143896" starttime="095720" supervisor_id="152332149" storeid="4" sbs="780030" opcode="153135959" date="20160915" endtime="111001">
 <CASHOPER managerid="153135959">
 <PAYMENT id="1" amount="3000.00" descr="CASH" tndnumb="1" exchangetndid="0">
  </PAYMENT>
  </CASHOPER>
  <LINKTRX linktype="8" prevstoreid="4" prevxactdate="2016-09-14" prevxacttime="22:58:29" prevtermid="0" prevxactid="7620" prevoperid="0"></LINKTRX>
 </TRX>
 <TRX type="16" term="743" trxnum="65729" saleperson="0" supervisor_id="153136068" storeid="4" sbs="780030" opcode="152332262" date="20160915" endtime="111219">
</TRX>

1 个答案:

答案 0 :(得分:0)

您应该选择所需的节点,然后将它们作为另一个元素的子节点附加,并将此元素作为新文档的根目录。请注意,第一个XPath表达式似乎不正确(可能它应该是 // TRX [@type = 16]

private Document daMethod(Document document, String xpath) throws Exception{
        List<Node> nodes = document.selectNodes(xpath);

        Element newRoot = DocumentHelper.createElement("TRXS");
        for (Node node : nodes) {
            newRoot.add((Node)node.clone());
        }

        return DocumentHelper.createDocument(newRoot);
    }

希望它有所帮助。