merge XML using STAX XMLStreamWriter

2019-08-14 06:19发布

I have created an XML using STAX and XMLStreamWriter. It works fine.

I need to merge two xml together. The problem that I am facing is the patient Pojo returns me XML containing all the patient information is below

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

I need to add this into existing XML after <proID> like merging.

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

Please advice

标签: java xml java-6
1条回答
我命由我不由天
2楼-- · 2019-08-14 07:02

The answer is as below

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 
查看更多
登录 后发表回答