JAXB Unmarshaling XML保留了CDATA

时间:2014-08-14 03:26:48

标签: xml jaxb xsd unmarshalling cdata

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

定义Product元素的XSD部分是:

<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的片段是:

<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,请在解组后(并将我导航到任何product.getDescription()个节点),我得到:

[CDATA[444 Ivory]]

444 Ivory

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

为什么CDATA包装器仍然存在?在我在本网站和其他网站上看到的每个例子中,它们都会在解组时被删除。这必须是一个简单的问题,但我只是没有看到它。

1 个答案:

答案 0 :(得分: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的任何内容以提供正确的语法。