Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 611
hiamex Avatar asked Nov 29 '12 13:11

hiamex


People also ask

Can XML documents have root element?

Each XML document has exactly one single root element. It encloses all the other elements and is, therefore, the sole parent element to all the other elements.

What is a root element in XML?

The XML root element represents the XML document that is being mapped. The XML root element is a looping structure that contains elements and content particles that repeat in sequence until either the group data ends or the maximum number of times that the loop is permitted to repeat is exhausted.

Can XML have 2 root elements?

While a properly formed XML file can only have a single root element, an XSD or DTD file can contain multiple roots.


1 Answers

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>
like image 142
jtahlborn Avatar answered Nov 09 '22 18:11

jtahlborn