【问题标题】:JAXB unmashalling cdataJAXB 解组 cdata
【发布时间】:2013-03-19 21:59:44
【问题描述】:

我不需要编组器,我已经有了 XML 文件。所以我关注this guide 来了解如何解组 CDATA 中的内容。但是,我发现,如果我跳过主要的编组部分而只做解组部分,它似乎不起作用。所以我的主要只是如下

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

我希望看到 CDATA 中的任何内容。我确定我遗漏了一些东西,但不确定是什么。

【问题讨论】:

    标签: java jaxb unmarshalling cdata


    【解决方案1】:

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

    【讨论】:

    • @user2167013 - 您可以单击答案旁边的复选标记来标记您的问题已解决。
    猜你喜欢
    • 2011-11-24
    • 2012-12-21
    • 2014-10-07
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2014-09-29
    • 1970-01-01
    相关资源
    最近更新 更多