要解组带有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>