Here’s a trivial excerpt from my XSD file
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="ns"
xmlns:tns="sns" elementFormDefault="qualified">
<element name="document">
<attribute name="title" use="required"/>
</element>
</schema>
I use the maven-jaxb2-plugin to generate Java classes from this. The Document class has a getTitle() method to return the text of the title attribute.
I want to add an additional method to Document:
public String getStrippedTitle() {
return getTitle().replaceAll("\\s+", "");
}
I want my extra method to appear on the unmarshalled object (rather than me just calling it or writing a wrapper class) because I want to pass the top-level unmarshalled object off to a string template and have it iterate over sub-elements calling my extra method.
I found instructions but they tell me to set a property on the Unmarshaller and my (Mac OS X, Java 7) implementation doesn’t appear to support any properties.
How should I do this?
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
DocumentExinstead ofDocument.DocumentExis a class I create, which looks like this: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:There is some (hard-to-parse) documentation for this at Oracle and some helpful examples at O’Reilly.