I have a method which returns a String
with a formatted xml. The method reads the xml from a file on the server and parses it into the string:
Esentially what the method currently does is:
private ServletConfig config;
InputStream xmlIn = null ;
xmlIn = config.getServletContext().getResourceAsStream(filename + ".xml") ;
String xml = IOUtils.toString(xmlIn);
IOUtils.closeQuietly(xmlIn);
return xml;
What I need to do is add a new input argument, and based on that value, continue returning the formatted xml, or return unformatted xml.
What I mean with formatted xml is something like:
<xml>
<root>
<elements>
<elem1/>
<elem2/>
<elements>
<root>
</xml>
And what I mean with unformatted xml is something like:
<xml><root><elements><elem1/><elem2/><elements><root></xml>
or:
<xml>
<root>
<elements>
<elem1/>
<elem2/>
<elements>
<root>
</xml>
Is there a simple way to do this?
You can: 1) remove all consecutive whitespaces (but not single whitespace) and then replace all >(whitespace)< by >< applicable only if usefull content does not have multiple consecutive significant whitespaces 2) read it in some dom tree and serialize it using some nonpretty serialization
3) use Canonicalization (but you must somehow explain to it that those whitespaces you want to remove are insignificant)
If you fancy trying your hand with JAXB then the marshaller has a handy property for setting whether to format (use new lines and indent) the output or not.
Quite an overhead to get to that stage though... perhaps a good option if you already have a solid xsd
if you are sure that the formatted xml like:
you can replace all group 1 in
^(\s*)<
to "". in this way, the text in xml won't be changed.an empty transformer with a parameter setting the indent params like so
works for me.
the key lies in this line
Strip all newline characters with
String xml = IOUtils.toString(xmlIn).replace("\n", "")
. Or\t
to keep several lines but without indentation.Try something like the following:
Instead of source being
StreamSource
in the second instance, it can also beDOMSource
if you have an in-memoryDocument
, if you want to modify the DOM before saving.DOMSource source = new DOMSource(document);
To read an XML file into a
Document
object:Enjoy :)