user2167013
user2167013

Reputation: 359

JAXB unmashalling cdata

I do not need a marshaller, I already got XML files. So I was following this guide to see how to unmarshall the content in the CDATA . But, I found, it doesn't seem to work if I skip the marshalling part in the main and do only the unmarshalling part. So my main is only like the following

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

I expect to see whatever in the CDATA. I am sure I am missing something but not sure what.

Upvotes: 4

Views: 5573

Answers (1)

bdoughan
bdoughan

Reputation: 149047

There is noting special you need to do to unmarshal an XML element with CDATA. Below is a simplified version of the demo from the article you cited.

input.xml

The description element below has a element with 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>

Book

Below is the Java class that we will unmarshal the XML content to,

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;
    }

}

Demo

The demo code below converts the XML to an instance of 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());
    }

}

Output

Below is the value of the description property.

<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>

Upvotes: 7

Related Questions