问题描述
所以这是我的问题.我得到了一个 XSD,我生成的 XML 文件应该遵守该 XSD.使用 org.apache.cxf.cxf-xjc-plugin
maven 插件和外部绑定文件生成源代码.但是当我尝试编组我的对象时,生成的 XML 不符合我的要求.
So here's my problem. I'm given an XSD to which my generated XML file should comply. Using the org.apache.cxf.cxf-xjc-plugin
maven plugin and an external binding file I generate the source code. But when I'm trying marshall my object the generated XML doesn't meet my requirements.
我的 XSD 包含以下内容:
My XSD contains the following:
<xsd:element maxOccurs="1" minOccurs="0" name="amount">
<xsd:simpleType>
<xsd:restriction base="xsd:decimal">
<xsd:totalDigits value="13" />
<xsd:fractionDigits value="2" />
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
...
<xsd:element maxOccurs="1" minOccurs="0" name="rate">
<xsd:simpleType>
<xsd:restriction base="xsd:decimal">
<xsd:totalDigits value="8" />
<xsd:fractionDigits value="5" />
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
生成的 XML 片段如下所示:
And the generated piece of XML looks like this:
<amount>109.5</amount>
...
<rate>10.25</rate>
虽然我期待它是:
<amount>109.50</amount>
...
<rate>10.25000</rate>
有没有办法以干净的方式解决这个问题?
Is there a way to solve this problem in a clean way?
我不希望为每个 totalDigits
、fractionDigits
组合编写多个适配器.由于 XSD 可能会发生变化,我想保持生成的源代码不变.
I would prefer not writing several adapters for every single totalDigits
, fractionDigits
combination. And as the XSD is subject to change I'd like to leave the generated source code untouched.
推荐答案
对于这个用例,您需要使用 XmlAdapter
.下面是一个示例绑定文件,可帮助您生成它们.逻辑将包含在 DecimalFormatter
类中,该类包含所有不同所需格式的方法.
You will need to use XmlAdapter
for this use case. Below is a sample binding file that will help you generate them. The logic would be contained in a DecimalFormatter
class that contained methods for all the different required formats.
<jxb:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb" version="2.1">
<jxb:bindings schemaLocation="schema.xsd">
<jxb:bindings node="//xs:element[@name='amount']">
<jxb:property>
<jxb:baseType>
<jxb:javaType name="java.math.BigDecimal"
parseMethod="org.example.DecimalFormatter.parseDecimal"
printMethod="org.example.DecimalFormatter.printDecimal_2Places" />
</jxb:baseType>
</jxb:property>
</jxb:bindings>
<jxb:bindings node="//xs:element[@name='rate']">
<jxb:property>
<jxb:baseType>
<jxb:javaType name="java.math.BigDecimal"
parseMethod="org.example.DecimalFormatter.parseDecimal"
printMethod="org.example.DecimalFormatter.printDecimal_5Places" />
</jxb:baseType>
</jxb:property>
</jxb:bindings>
</jxb:bindings>
</jxb:bindings>
更多信息
- http://blog.bdoughan.com/2011/08/xml-schema-to-java-generating.html
这篇关于使用 fractionDigits 对 BigDecimal 进行 JAXB 编组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!