How to remove Namespace and Nillable properties in generated XML by marshalling through JAXB

前端 未结 1 1133
一生所求
一生所求 2021-01-23 03:22

I have following XSD file:-

   
   

        
相关标签:
1条回答
  • 2021-01-23 03:32

    Java Model

    I generated the default Java model from your XML Schema using XJC.

    Demo Code

    Demo

    The demo code below populates the object model (setting the centralCaseID property to null) and marshals it to XML.

    import javax.xml.bind.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance("emp");
    
            ObjectFactory objectFactory = new ObjectFactory();
            Root root = objectFactory.createRoot();
    
            CaseDetail caseDetail = objectFactory.createCaseDetail();
            caseDetail.setCentralCaseID(null);
            root.getCaseDetail().add(caseDetail);
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(root, System.out);
        }
    
    }
    

    Output

    Below is the output from running the demo code.

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <root xmlns="emp">
        <Case_Detail/>
    </root>
    

    Items to note:

    • A namespace declaration was written out. This is because the @XmlSchema annotation is present on the package-info class that maps the namespace qualification (see: http://blog.bdoughan.com/2010/08/jaxb-namespaces.html).

      @javax.xml.bind.annotation.XmlSchema(
          namespace = "emp", 
          elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
      package emp;
      
    • The element corresponding to the centralCaseID property does not appear in the XML. This is the default behaviour regarding null properties (see: http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html).

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