java – JAXB unmashalling cdata
作者:互联网
我不需要marshaller,我已经有了XML文件.所以我在关注this guide以了解如何解组CDATA中的内容.但是,我发现,如果我跳过主要的编组部分并且只做解组部分,它似乎不起作用.所以我的主要内容仅限于以下内容
Book book2 = JAXBXMLHandler.unmarshal(new File("book.xml"));
System.out.println(book2); //<-- return null.
我期待看到CDATA中的任何内容.我确信我错过了一些东西,但不确定是什么.
解决方法:
使用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>
标签:java,jaxb,unmarshalling,cdata 来源: https://codeday.me/bug/20190613/1229756.html