使用STAX XMLStreamWriter合并XML

时间:2014-02-12 09:58:27

标签: java xml java-6

我使用XML和XMLStreamWriter创建了STAX。它工作正常。

我需要将两个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>

请咨询

1 个答案:

答案 0 :(得分: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