将不对称XML拆分为多个XML

时间:2015-07-10 21:55:38

标签: java xml xpath

我必须在' Trade'上拆分不对称的xml。元素使用java

'<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<BookingRequest>      
   <Id>1234</Id>
   <App>Pan</App>
   <Parties>
     <Party>1</Party>
     <Party>2</Party>
   </Parties>
   <Contract>
      <Trades>
        <Trade>
            <Detail>100</Detail>
            <Location>
                <Num>10001</Num>
            </Location>
         </Trade>           
         <Trade>
            <Detail>101</Detail>
            <Location>
                <Num>10002</Num>
            </Location>
        </Trade>
      </Trades>
   </Contract>
</BookingRequest>

我的要求是分拆后应该有2个文件:

文件1:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<BookingRequest>      
   <Id>1234</Id>
   <App>Pan</App>
   <Parties>
     <Party>1</Party>
     <Party>2</Party>
   </Parties>
   <Contract>
      <Trades>
        <Trade>
            <Detail>100</Detail>
            <Location>
                <Num>10001</Num>
            </Location>
        </Trade>
      </Trades>
   </Contract>
</BookingRequest>

文件2:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<BookingRequest>      
   <Id>1234</Id>
   <App>Pan</App>
   <Parties>
     <Party>1</Party>
     <Party>2</Party>
   </Parties>
   <Contract>
      <Trades>
        <Trade>
            <Detail>101</Detail>
            <Location>
                <Num>10002</Num>
            </Location>
         </Trade>
      </Trades>
   </Contract>
</BookingRequest>

有人可以帮我做这种分裂(最好使用DOM / XPath而不是XSLT)

1 个答案:

答案 0 :(得分:0)

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse("booking-request.xml");
Element bookingRequest = doc.getDocumentElement();
Element contract = (Element)bookingRequest.getElementsByTagName("Contract").item(0);
Element trades = (Element)contract.getElementsByTagName("Trades").item(0);

List<Element> tradeList = new ArrayList<Element>();
NodeList nodeList = trades.getElementsByTagName("Trade");
for(int i=0; i<nodeList.getLength(); i++)
    tradeList.add((Element)nodeList.item(i));

Transformer transformer = TransformerFactory.newInstance().newTransformer();
int i = 0;
for(Element trade: tradeList){
    // remove all children of <Trades>
    while(trades.getFirstChild()!=null)
        trades.removeChild(trades.getFirstChild());

    trades.appendChild(doc.createTextNode("\n            "));
    trades.appendChild(trade);
    trades.appendChild(doc.createTextNode("\n        "));
    ++i;
    transformer.transform(new DOMSource(doc), new StreamResult(new File("trade"+i+".xml")));
}