我必须使用 java 在“Trade”元素上拆分不对称的 xml
'<?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)
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")));
}
我是一名优秀的程序员,十分优秀!