向从模式生成的 JAXB 类添加额外的方法
这是我的 XSD 文件的一个简单的摘录
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>
我使用 maven-jaxb2-plugin
从中生成 Java 类.Document
类有一个 getTitle()
方法来返回 title
属性的文本.
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.
我想在 Document
中添加一个额外的方法:
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.
我找到了 说明,但他们告诉我在 Unmarshaller
上设置一个属性,而我的(Mac OS X、Java 7)实现似乎不支持任何属性.
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.
我应该怎么做?
推荐答案
按照 Brian Henry 提供的链接,我发现我可以在我的模式文件中内联执行绑定自定义来做我想做的事.效果和Brian的方案一模一样,但是不需要引用com.sun.xml.internal
的引用.
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:
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="ns"
xmlns:tns="sns" elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0">
<element name="document">
<annotation>
<appinfo>
<jaxb:class implClass="DocumentEx" />
</appinfo>
</annotation>
<attribute name="title" use="required"/>
</element>
</schema>
当模式被编译成 Java 代码时,生成的 ObjectFactory 将引用 DocumentEx
而不是 Document
.DocumentEx
是我创建的一个类,如下所示:
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
(我正在扩展的类)仍然由 schema-to-Java 编译器生成.现在,当我解组文档时,我实际上得到了一个 DocumentEx 对象:
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);
在 Oracle 以及 O'Reilly.
相关文章