Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the XML header from an XML in Java

Tags:

java

xml

StringWriter  writer = new StringWriter(); XmlSerializer serializer = new KXmlSerializer(); serializer.setOutput(writer); serializer.startDocument(null, null); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); // Creating XML  serializer.endDocument(); String xmlString = writer.toString(); 

In the above environment, whether there are any standard API's available to remove the XML header <?xml version='1.0' ?> or do you suggest to go via string manipulation:

if (s.startsWith("<?xml ")) {     s = s.substring(s.indexOf("?>") + 2); } 

Wanted the output in the xmlString without XML header info <?xml version='1.0' ?>.

like image 763
Babu Avatar asked Apr 11 '11 03:04

Babu


People also ask

Does XML need a header?

This header must appear on the first line of all XML documents; therefore, all XML Grammar documents (fileName. grxml) must have the XML header at the top.

What is header XML?

The XML header specifies the XML version number, and optionally the character encodings, as part of a grammar document's XML declaration on the first line of the document.


1 Answers

Ideally you can make an API call to exclude the XML header if desired. It doesn't appear that KXmlSerializer supports this though (skimming through the code here). If you had a org.w3c.dom.Document (or actually any other implementation of javax.xml.transform.Source) you could accomplish what you want this way:

TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); 

Otherwise if you have to use KXmlSerializer it looks like you'll have to manipulate the output.

like image 182
WhiteFang34 Avatar answered Sep 18 '22 14:09

WhiteFang34