I’m starting to use the Simple XML framework with annotations (link) for Java, but I don’t get, how to prelude the XML declaration tag <?xml version="1.0" encoding="UTF-8" ?> in the XML file. So my question is: How do I get the XML declaration as first tag?
package simplexml;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root
public class Example {
@Element
private String text;
@Attribute
private int index;
public Example(String text, int index) {
this.text = text;
this.index = index;
}
public String getMessage() {
return text;
}
public int getId() {
return index;
}
}
Test:
public static void main(String[] args) {
Serializer serializer = new Persister();
Example example = new Example("Example message", 123);
File result = new File("example.xml");
try {
serializer.write(example, result);
} catch (Exception e) {
e.printStackTrace();
}
}
Produces:
<example index="123">
<text>Example message</text>
</example>
What I’d like to have:
<?xml version="1.0" encoding="UTF-8" ?>
<example index="123">
<text>Example message</text>
</example>
Thanks! Also, where could I look such things up?
I use Spring for Android to send XML requests, and was facing the same problem. Here’s the code to get it work based on @implicit_knowledge’s solution in case anyone needs it.