gpt4 book ai didi

java - 使用 STAX XMLStreamWriter 合并 XML

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:40 25 4
gpt4 key购买 nike

我创建了一个XML使用STAX和 XMLStreamWriter。效果很好。

我需要将两个 xml 合并在一起。我面临的问题是患者 Pojo 返回给我包含所有患者信息的 XML,如下

   <Patient>
<SocialSecurity>3333344</SocialSecurity>
<Name>
<LastName>pillai</LastName>
<FirstName>dhanya</FirstName>
<Name>
<Patient>

我需要将其添加到 <proID> 之后的现有 XML 中就像合并一样。

<?xml version="1.0" ?>
<Validate>
<proID>123</prodID>
</Validate>

请指教

最佳答案

答案如下

public static void main(String[] args) throws Throwable {
XMLEventWriter eventWriter;
XMLEventFactory eventFactory;
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
eventWriter = outputFactory.createXMLEventWriter(bos);
eventFactory = XMLEventFactory.newInstance();
XMLEvent newLine = eventFactory.createDTD("\n");
// Create and write Start Tag
StartDocument startDocument = eventFactory.createStartDocument();
eventWriter.add(startDocument);
eventWriter.add(newLine);
StartElement configStartElement = eventFactory.createStartElement("","","Message");
eventWriter.add(configStartElement);
eventWriter.add(newLine);

XMLInputFactory inputFactory = XMLInputFactory.newFactory();


PatientDetails patientDetails= new PatientDetails();// Here I have called an POJO that return String and we add
String xml = patientDetails.getPatientDetails();

Source src = new StreamSource(new java.io.StringReader(xml));

XMLEventReader test = inputFactory.createXMLEventReader(src);
while(test.hasNext()){
XMLEvent event= test.nextEvent();
//avoiding start(<?xml version="1.0"?>) and end of the documents;
if (event.getEventType()!= XMLEvent.START_DOCUMENT && event.getEventType() != XMLEvent.END_DOCUMENT)
eventWriter.add(event);
// eventWriter.add(newLine);
test.close();
} //end of while

eventWriter.add(eventFactory.createEndElement("", "", "Message"));
eventWriter.add(newLine);
eventWriter.add(eventFactory.createEndDocument());
eventWriter.close();

System.out.println(bos.toString());
}//end of main

关于java - 使用 STAX XMLStreamWriter 合并 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21724468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com