Adding extra methods to a JAXB class generated from schema

后端 未结 2 1209
无人共我
无人共我 2021-01-12 03:58

Here\'s a trivial excerpt from my XSD file




        
2条回答
  •  余生分开走
    2021-01-12 04:42

    Following the link the Brian Henry gave, I found I could perform binding customization inline in my schema file to do what I wanted. The effect is exactly the same as Brian's solution, but it doesn't require a reference to a reference to com.sun.xml.internal.

    First, the schema file gets modified somewhat:

    
    
      
          
              
                  
              
          
          
      
    
    

    When the schema gets compiled into Java code, the generated ObjectFactory will refer to DocumentEx instead of Document. DocumentEx is a class I create, which looks like this:

    public class DocumentEx extends Document {
       public String getStrippedTitle() {
           return getTitle().replaceAll("\\s+", "");
       }
    }
    

    Document (the class I'm extending) is still generated by the schema-to-Java compiler. Now when I unmarshall a document I actually get a DocumentEx object:

        JAXBContext jaxbContext = JAXBContext.newInstance("com.example.xml");
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(testSchema);
        DocumentEx doc = (DocumentEx)unmarshaller.unmarshal(xmlFile);
    

    There is some (hard-to-parse) documentation for this at Oracle and some helpful examples at O'Reilly.

提交回复
热议问题