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?
XML declaration contains details that prepare an XML processor to parse the XML document. It is optional, but when used, it must appear in the first line of the XML document.
The XML declaration is a processing instruction that identifies the document as being XML. All XML documents should begin with an XML declaration.
Example #2 Create a SimpleXMLElement object from a URL$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE); echo $sxe->asXML();
XML Naming Rules Element names cannot start with the letters xml (or XML, or Xml, etc) Element names can contain letters, digits, hyphens, underscores, and periods. Element names cannot contain spaces.
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.
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
Serializer serializer = new Persister(new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>"));
restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter(serializer));
restTemplate.postForObject(URL, udata, String.class);
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