需要特別注意的是,您需要使用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>
書
下面是Java類,我們將解組XML內容,
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>
是的,它的工作。謝謝 – user2167013 2013-03-21 17:02:28
@ user2167013 - 您可以點擊答案旁邊的選中標記,表示問題已解決。 – 2013-03-21 17:28:42