Complex XML using Spring Batch; StaxEventItemWriter ; Jaxb2Marshaller

后端 未结 1 1545
甜味超标
甜味超标 2021-01-20 20:21

I need to write a slightly complex XML using Spring Batch. Can anyone please help me with the appropriate Spring configuration?

Below is the Output the process requi

1条回答
  •  伪装坚强ぢ
    2021-01-20 20:54

    The solution to this problem is to implement Header/Footer Callback classes provided by Spring (As Michael Minella suggested in the comments below.), StaxWriterCallback class in my case. Below is How I've implemented it.

    
        
        
        
        
        
        
        
     
    
    
    
    
      
         
         
           org.test.model.xml.User
        
        
        
    

    And below are the Footer/Header callback classes implementation

     public class UserXMLHeaderCallBack implements StaxWriterCallback{  
          @Override
            public void write(XMLEventWriter writer) throws IOException {
                try{
                XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    
                Attribute id = eventFactory.createAttribute("ID", "someId");
                Attribute name = eventFactory.createAttribute("NAME", "someName");
                List attributeList = Arrays.asList(id, name);
                List nsList = Arrays.asList();
    
                XMLEvent event = eventFactory.createStartElement("", "", "USERLIST",attributeList.iterator(), nsList.iterator());
                writer.add(event);
    
                }catch(XMLStreamException e){
                    System.err.println("Something went nuts!!!");
                }
            }
    
        }
    

    Footer class

     public class UserXMLFooterCallBack implements StaxWriterCallback{
    
        @Override
        public void write(XMLEventWriter writer) throws IOException {
            try{
                XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    
                XMLEvent event = eventFactory.createEndElement("", "", "USERLIST");
                writer.add(event);
            }catch(XMLStreamException e){
                System.err.println("Something went nuts!!!");
            }
        }
    
    }
    

    And I got the desired Output!

    0 讨论(0)
提交回复
热议问题