JAXB unmashalling cdata

use*_*013 4 java jaxb cdata unmarshalling

我不需要marshaller,我已经有了XML文件.所以我按照本指南来了解如何解组CDATA中的内容.但是,我发现,如果我跳过主要的编组部分并且只做解组部分,它似乎不起作用.所以我的主要内容仅限于以下内容

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

我期待看到CDATA中的任何内容.我确信我错过了一些东西,但不确定是什么.

bdo*_*han 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>
Run Code Online (Sandbox Code Playgroud)

下面是我们将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;
    }

}
Run Code Online (Sandbox Code Playgroud)

演示

下面的演示代码将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());
    }

}
Run Code Online (Sandbox Code Playgroud)

产量

以下是该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>
Run Code Online (Sandbox Code Playgroud)