-1

I want to create new Xml file from the select nodes only i am using dom4j to parse and create new xml file. Example lets assume Nodes Customer name = Joseph is the child of root element TRX i want to show the whole elements that contain joseph and create a new file

     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 Answers1

0

You should select the nodes you need, then append them as children of another element and put this element as root of a new document. Note that first XPath expression seems incorrect (maybe it should be //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);
    }

Hope it helps.

eltabo
  • 3,749
  • 1
  • 21
  • 33