【问题标题】:JAVA - Unmarshal XML doc to objectJAVA - 将 XML 文档解组为对象
【发布时间】:2013-12-09 11:47:37
【问题描述】:

我的问题与其他人之前提出的问题相似,但事实是我还无法解决我的问题。 我有一个 XML 文档,我需要将它转换(解组)为一个对象,并且我正在使用 JAXB 注释来做这件事。到目前为止,一切都很好,但是我无法从中获得价值。 让我编码而不是说话。

我的 Java 对象:

@XmlRootElement
public class Product {
    private String date_upd;
    private MetaDescription meta_description;

    //------------Static classes for sub nodes------------------
    @XmlAccessorType(XmlAccessType.FIELD)
    static class MetaDescription{
        private List<Language> language ;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    static class Language{
        @XmlAttribute(name="id")
        private String id;
        @XmlValue
        private String language = null;
        void setLanguage(String language){
            this.language = language;
        }
        String getLanguage(){
            return this.language;
        }
    }


     public String getDate_upd() {
        return date_upd;
    }

    /**
     * @param date_upd the date_upd to set
     */
    @XmlElement
    public void setDate_upd(String date_upd) {
        this.date_upd = date_upd;
    }

    /**
     * @return the meta_description
     */
    public MetaDescription getMeta_description() {
        return meta_description;
    }

    /**
     * @param meta_description the meta_description to set
     */
    @XmlElement
    public void setMeta_description(MetaDescription meta_description) {
        this.meta_description = meta_description;
    }

}

我的 XML 文档有以下片段:

<product>
  <date_upd>
    <![CDATA[2013-12-06 18:03:59]]>
  </date_upd>
  <meta_description>
    <language id="1" xlink:href="http://demo1.it2care.com/shop/api/languages/1">
      <![CDATA[product1]]>
    </language>
    <language id="2" xlink:href="http://demo1.it2care.com/shop/api/languages/2">
      <![CDATA[produto1]]>
    </language>
  </meta_description>
</product>

它有更多的属性,但只有这些是相关的。 'date_upd' 正在正确解组,但我无法为 'meta_description' 解决它。我在“元描述”字段中获得了“语言”对象的列表,但我无法获得“语言”的值,尽管我从“语言”节点获得了“id”属性。 对于呈现的 XML 示例,“meta_description”是一个包含 2 个元素的列表。在两个列表元素上,“ID”都已正确填写,但我从“语言”中得到“”,而不是“产品1”。

有什么提示吗?提前非常感谢。

【问题讨论】:

    标签: java xml jaxb


    【解决方案1】:

    我想我明白了!我得到了语言的“”,因为我的节点里面有 CDATA 元素。出于某种原因,我仍在试图弄清楚,解组器没有进入这些节点,因此返回一个空字符串。 我解决了问题的根源。在将 XML 字符串从服务器转换为 XML 文档时,我添加了以下片段:

    //Create a Document factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //Line I added
    factory.setCoalescing(true); //remove all CDATA wrappers
    

    这解决了我的问题,使用我最初发布的结构。 希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 2010-11-23
      • 2011-11-08
      • 2015-09-12
      • 2016-12-02
      相关资源
      最近更新 更多