2014-02-12 32 views
1

我使用和XMLStreamWriter創建了XML。它工作正常。使用STAX XMLStreamWriter合併XML

我需要將兩個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> 

請指點

+0

是最後'Name'和'Patient'在第一位的標籤應該是結束標籤? –

+0

對於那些正在尋找答案。 – CodingPerson

回答

1

答案是如下

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