【发布时间】:2015-05-26 08:05:44
【问题描述】:
我正在使用 JAXB 来处理来自 XML 文件的数据并将这些值插入到数据库中。我在从特定 XML 标记中提取数据时遇到问题。
此 XML 标记包含字母数字值,但大约 95%(如果不是 99%)的时间,它包含的值是整数。因此,我将这些值视为String。
<reference>12345</reference>
而且,数据库中对应的列是varchar。
我创建了一个XSD 文件,确保元素reference 的类型为xsd:string
<xs:element name="reference" type="xs:string" />
问题是我可以有一个 XML 文件,其中一些引用是这种格式的:
<reference>012345</reference>
<reference>0012345</reference>
提取这些引用的值会删除前导零,给我12345 作为结果值。我不明白为什么。我觉得 JAXB 将值视为整数。
我怎样才能获得正确的价值观?
编辑:
这是对应的 POJO @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "referenceOrDescriptionOrEnseignes" }) 公共静态类程序 {
@XmlElementRefs({
@XmlElementRef(name = "reference", type = JAXBElement.class, required = false),
/** other @XmlElementRef */
})
protected List<JAXBElement<?>> referenceOrDescriptionOrEnseignes;
有趣的是,在上述变量的 get 方法中,JAXB 指定了允许进入列表的对象。只允许使用由 JAXB 使用 XSD 文件创建的 String 和其他 POJO 对象。不允许提及Integers。
/**
* Gets the value of the referenceOrDescriptionOrEnseignes property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the referenceOrDescriptionOrEnseignes property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getReferenceOrDescriptionOrEnseignes().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link String }{@code >}
* ...
* ...
* ...
*/
public List<JAXBElement<?>> getReferenceOrDescriptionOrEnseignes() {
if (referenceOrDescriptionOrEnseignes == null) {
referenceOrDescriptionOrEnseignes = new ArrayList<JAXBElement<?>>();
}
return this.referenceOrDescriptionOrEnseignes;
}
奇怪的是,当我打印引用元素的类类型时,它会打印Integer。
谢谢!
【问题讨论】:
-
对应的包含
reference元素的POJO看起来如何? -
@Petter:检查我编辑的问题。
-
我不明白你为什么得到
JAXBElements 而不是普通的Strings。这些类是使用 XSD 生成的吗? XSD 部分中的reference元素是choice元素还是类似元素? -
是的,我也不明白。是的,这些类是使用 XSD 生成的。
reference元素不是选择的一部分。它是另一个更大物体的一部分。哦,我刚刚注意到必需的属性是false,这是不对的。但那是另一回事了。 -
也许这个答案会有所帮助(至少在获取普通字符串方面):stackoverflow.com/questions/12508741/…