問題描述
所以這是我的問題.我得到了一個 XSD,我生成的 XML 文件應(yīng)該遵守該 XSD.使用 org.apache.cxf.cxf-xjc-plugin
maven 插件和外部綁定文件生成源代碼.但是當(dāng)我嘗試編組我的對象時,生成的 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 包含以下內(nèi)容:
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 可能會發(fā)生變化,我想保持生成的源代碼不變.
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="http://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="http://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
這篇關(guān)于使用 fractionDigits 對 BigDecimal 進(jìn)行 JAXB 編組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!