Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I pretty-print a well-formed invalid XML snippet in java?
    primarykey
    data
    text
    <p>I've tried</p> <pre><code>SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); XMLReader reader = factory.newSAXParser().getXMLReader(); Source xmlInput = new SAXSource(reader, new InputSource(new StringReader(xml))); StringWriter stringWriter = new StringWriter(); xmlPretty = new StreamResult(stringWriter); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlPretty); return xmlPretty.getWriter().toString(); </code></pre> <p>but as soon as there is an "ignorable space" the indentation stops. I've searched a lot but found nothing about ignorable spaces in sax parsers, except in Handlers. So I've tried to add a handler of mine:</p> <pre><code>class MyHandler extends DefaultHandler { @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { System.out.println("foo"); } } ... reader.setContentHandler(new MyHandler()); </code></pre> <p>but it never prints "foo".</p> <p>Update: Here is an example of input:</p> <pre><code>&lt;n:a&gt; &lt;b&gt;foo &lt;/b&gt; &lt;/n:a&gt; </code></pre> <p>So well-formed but invalid (n is not defined). I want the function to output something like:</p> <pre><code>&lt;n:a&gt; &lt;b&gt;foo &lt;/b&gt; &lt;/n:a&gt; </code></pre> <p>The program above does output this if I provide it with:</p> <pre><code>&lt;n:a&gt;&lt;b&gt;foo &lt;/b&gt;&lt;/n:a&gt; </code></pre> <p>But not with <code>&lt;n:a&gt; &lt;b&gt;foo &lt;/b&gt; &lt;/n:a&gt;</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload