【问题标题】:JAXB Unmarshaling XML Retains CDATAJAXB 解组 XML 保留 CDATA
【发布时间】:2014-10-07 14:28:53
【问题描述】:

我正在尝试解组包含 CDATA 元素的 XML。我得到的字符串仍然有 CDATA “包装器”。我使用 XJC 从 XSD 创建 Java 类,它们位于 jmish.jaxb 包中。我正在使用 Oracle(Sun 的)Java 7 JDK 中包含的 JAXB。

XSD 中定义Product 元素的部分是:

<xs:element name="Product" minOccurs="0" maxOccurs="unbounded">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="Specifications" minOccurs="0" maxOccurs="1" />
      <xs:element name="Description" type="xs:string" minOccurs="1" maxOccurs="1" msdata:Ordinal="1" />
    </xs:sequence>
    <xs:attribute name="name" type="xs:string" />
    <xs:attribute name="imageFile" type="xs:string" />
  </xs:complexType>
</xs:element>

XML 的 sn-p 是:

<Product name="Allure_444" imageFile="Allure_444_Ivory.jpg">
    <Description>![CDATA[444 Ivory]]</Description>
</Product>

解组代码是:

JAXBContext jc = JAXBContext.newInstance( "jmish.jaxb" );
Unmarshaller u = jc.createUnmarshaller();
Catalog catalog = (Catalog)u.unmarshal( new FileInputStream( "bin/ProductCatalog.xml" ) );

如果我调用product.getDescription(),在解组(并向下导航到任何Product 节点)后,我会得到:

[CDATA[444 Ivory]]

不是:

444 Ivory

如果 CDATA 包含任何字符实体,它们将被正确替换(因此任何 &amp;lt; 变为 &lt;)。

为什么 CDATA 包装器会持续存在?在我在此站点和其他站点上看到的每个示例中,它们都在解组过程中被删除。这一定是一个简单的问题,但我只是没有看到它。

【问题讨论】:

    标签: xml jaxb xsd unmarshalling cdata


    【解决方案1】:
    <Product name="Allure_444" imageFile="Allure_444_Ivory.jpg">
        <Description>![CDATA[444 Ivory]]</Description>
    </Product>
    

    这不是一个有效的 CDATA 包装器。它应该是这样的:

    <Product name="Allure_444" imageFile="Allure_444_Ivory.jpg">
        <Description><![CDATA[444 Ivory]]></Description>
    </Product>
    

    您需要修复生成 XML 的任何内容以提供正确的语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-24
      • 2013-03-19
      • 2019-08-08
      • 2012-12-21
      • 2015-03-25
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      相关资源
      最近更新 更多