hiamex
hiamex

Reputation: 315

How to parse an XML with only root element

I need to annotate a class for unmarshalling an XML like this:

<element>data</element>

And I don't know how to do it because the class has to be annotated with @XmlRootElement but I need to get the root element value. I know this doesn't work but it's what I have done:

@XmlRootElement(name = "element")
public Class MyClass{

@XmlElement(name = "element")
protected String elementValue;
public String getElementValue(){...}
public void setElementValue(String el){...}

Is there any possibility to get this?

Upvotes: 5

Views: 1606

Answers (1)

jtahlborn
jtahlborn

Reputation: 53694

You are looking for the @XmlValue annotation.

MyClass

package forum13626828;

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "element")
public class MyClass{

    protected String elementValue;

    @XmlValue
    public String getElementValue() {
        return elementValue;
    }

    public void setElementValue(String el) {
        this.elementValue = el;
    }

}

Demo

package forum13626828;

import java.io.StringReader;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(MyClass.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StringReader xml = new StringReader("<element>data</element>");
        MyClass myClass = (MyClass) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(myClass, System.out);
    }

}

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<element>data</element>

Upvotes: 13

Related Questions