您需要特别注意使用 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>