JAXB反序列化CDATA

4

我不需要一个marshaller,因为我已经有XML文件了。所以我按照这个指南来查看如何在CDATA中解组内容。但是,我发现,如果我跳过主要的编组部分,只做解组部分,它似乎不起作用。所以我的主要部分只像以下内容:

Book book2 = JAXBXMLHandler.unmarshal(new File("book.xml"));
System.out.println(book2);  //<-- return null. 

我希望能够在CDATA中看到所有的内容。我确信自己遗漏了某些东西,但不确定是什么。

1个回答

7

要解组带有CDATA的XML元素,您无需执行任何特殊操作。以下是来自您引用文章的演示的简化版本。

input.xml

下面的description元素具有一个包含CDATA的元素。

<?xml version="1.0" encoding="UTF-8"?>
<book>
    <description><![CDATA[<p>With hundreds of practice questions
        and hands-on exercises, <b>SCJP Sun Certified Programmer
        for Java 6 Study Guide</b> covers what you need to know--
        and shows you how to prepare --for this challenging exam. </p>]]>
    </description>
</book>

书籍

以下是我们将解组XML内容的Java类,

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Book {

    private String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

演示

以下演示代码将XML转换为Book实例。

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Book.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum15518850/input.xml");
        Book book = (Book) unmarshaller.unmarshal(xml);

        System.out.println(book.getDescription());
    }

}

输出

以下是description属性的值。

<p>With hundreds of practice questions
        and hands-on exercises, <b>SCJP Sun Certified Programmer
        for Java 6 Study Guide</b> covers what you need to know--
        and shows you how to prepare --for this challenging exam. </p>

1
@user2167013 - 你可以点击答案旁边的复选标记来标记你的问题已经解决。 - bdoughan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接