【问题标题】:Extracting values frm XML file using JAXB使用 JAXB 从 XML 文件中提取值
【发布时间】: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/…

标签: java xml xsd jaxb


【解决方案1】:

您能否在插入数据库之前尝试打印此值。

交叉检查您的 POJO。

【讨论】:

  • 是的,我打印了这些值,它们没有前导零。我编辑了我的问题以添加 POJO。
猜你喜欢
  • 2014-10-16
  • 2011-10-13
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多