这是我的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+", "");
}
我希望我的额外方法出现在unmarshalled对象上(而不是我只是调用它或编写一个包装类)因为我想将顶层的unmarshalled对象传递给一个字符串模板并让它迭代调用我的子元素额外的方法.
我找到了instructions,但他们告诉我在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>
当模式编译成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有一些有用的例子.
标签:java,jaxb 来源: https://codeday.me/bug/20191007/1869585.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。