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?
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.
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.
While a properly formed XML file can only have a single root element, an XSD or DTD file can contain multiple roots.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With