How to generate end tag for empty element in XML using JAXB

前端 未结 3 653
死守一世寂寞
死守一世寂寞 2021-01-18 00:37

I\'m generating XML using JAXB. But JAXB is generating an empty Tag closing it self. But my client want separate empty tag. I know both are equals but he is not agree with m

相关标签:
3条回答
  • 2021-01-18 01:31

    If you have generated Classes from XSD then you would also generated ObjectFactory class. If don't please refer here about how to generate ObjectFactory class.

    After that, your code would be like--

    JAXBContext context;
                context = JAXBContext.newInstance(*yourClass*.class);
    
    final ObjectFactory objFactory = new ObjectFactory();
    
                final JAXBElement<YourClass> element = objFactory
                        .*autoGeneratedmethodfromObjectFactorytogetelement*;
    
    Marshaller marshaller;
                marshaller = context.createMarshaller();
    
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                        Boolean.TRUE);
                final StringWriter stringWriter = new StringWriter();
    
    
                marshaller.marshal(element, stringWriter);
              String message = stringWriter.toString();
    

    This will give you desired output.

    0 讨论(0)
  • 2021-01-18 01:33

    Problem solved, To force a closing tag, just add an empty String as the value of this tag ! You can do it using @XmlValue :

    public class closedTag {
    
        @XmlValue
        private String content;
    
    
        public closedTag() {
            this.content = "";
        }
    
    }
    
    0 讨论(0)
  • 2021-01-18 01:36

    This behaviour is implementation dependant. I stumbled into opposite problem (I needed self-closing tag) and I resolved in this way.
    You can try using this version of marshal() or modifying code from linked answer.

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