这是我的 XSD 文件的一小段摘录
<?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
属性。
我想添加一个额外的方法Document
:
public String getStrippedTitle() {
return getTitle().replaceAll("\\s+", "");
}
我希望我的额外方法出现在未编组的对象上(而不是我只是调用它或编写包装类),因为我想将顶级未编组对象传递给字符串模板,并让它迭代调用我的子元素额外的方法。
I found 指示但他们告诉我要设置一个属性Unmarshaller
我的(Mac OS X,Java 7)实现似乎不支持任何属性。
我该怎么做?
按照 Brian Henry 提供的链接,我发现我可以在架构文件中内联执行绑定自定义来执行我想要的操作。效果和Brian的解决方案一模一样,但是不需要引用com.sun.xml.internal
.
首先,架构文件进行了一些修改:
<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>
当 schema 被编译成 Java 代码时,生成的 ObjectFactory 将引用DocumentEx
代替Document
. DocumentEx
是我创建的一个类,如下所示:
public class DocumentEx extends Document {
public String getStrippedTitle() {
return getTitle().replaceAll("\\s+", "");
}
}
Document
(我正在扩展的类)仍然由 schema-to-Java 编译器生成。现在,当我解组文档时,我实际上得到了一个 DocumentEx 对象:
JAXBContext jaxbContext = JAXBContext.newInstance("com.example.xml");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(testSchema);
DocumentEx doc = (DocumentEx)unmarshaller.unmarshal(xmlFile);
有一些(难以解析的)文档位于Oracle以及一些有用的例子O'Reilly.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)