Pretty printing XML with javascript
From the text of the question I get the impression that a string result is expected, as opposed to an HTML-formatted result.
If this is so, the simplest way to achieve this is to process the XML document with the identity transformation and with an <xsl:output indent="yes"/>
instruction:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
When applying this transformation on the provided XML document:
<root><node/></root>
most XSLT processors (.NET XslCompiledTransform, Saxon 6.5.4 and Saxon 9.0.0.2, AltovaXML) produce the wanted result:
<root>
<node />
</root>
How to print pretty xml in javascript?
This does not take care of any indenting, but helps to encode the XML for use within <pre>
or <textarea>
tags:
/* hack to encode HTML entities */
var d = document.createElement('div');
var t = document.createTextNode(myXml);
d.appendChild(t);
document.write('<pre>' + d.innerHTML + '</pre>');
And if, instead of a <textarea>
, you'd want highlighting and the nodes to be collapsable/expandable, then see Displaying XML in Chrome Browser on Super User.
How to format an XML string with line breaks using Javascript?
If there is no text between the xml-tags
like in the example you presented (e.g. <foo><bar></foo>
and not <foo>Some Text</foo>
) one can simply do the following:
xmlStr.replaceAll(">",">\n")
which results in
<?xml version="1.0"?>
<?meta name="test"?>
<Foo>
<Bar>
<FooBar/>
</Bar>
</Foo>
How to pretty print XML from Java?
Now it's 2012 and Java can do more than it used to with XML, I'd like to add an alternative to my accepted answer. This has no dependencies outside of Java 6.
import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
/**
* Pretty-prints xml, supplied as a string.
* <p/>
* eg.
* <code>
* String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
* </code>
*/
public class XmlFormatter {
public String format(String xml) {
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));
//May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.
return writer.writeToString(document);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
String unformattedXml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +
" xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +
" xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +
" <Query>\n" +
" <query:CategorySchemeWhere>\n" +
" \t\t\t\t\t <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +
" </query:CategorySchemeWhere>\n" +
" </Query>\n\n\n\n\n" +
"</QueryMessage>";
System.out.println(new XmlFormatter().format(unformattedXml));
}
}
Pretty-print Java, XML, JavaScript, ... to HTML
Checkout google-code-prettify, which is used here on Stack Overflow and code.google.com. It works with Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, Makefiles, and Rust. You can see samples in its Gallery of themes.
Related Topics
String.Replace' Weird Behavior When Using Dollar Sign ($) as Replacement
Unexpected Behavior Using Array Map on an Array Initialized with Array Fill
How to Remove All the Options of a Select Box and Then Add One Option and Select It with Jquery
Prototype Based VS. Class Based Inheritance
Get Viewport/Window Height in Reactjs
What Is the Instanceof Operator in JavaScript
Functions That Return a Function
Convert a Binary Nodejs Buffer to JavaScript Arraybuffer
Start Script Missing Error When Running Npm Start
How to Watch for Array Changes
Parallel Asynchronous Ajax Requests Using Jquery
Jquery Disable Form Submit on Enter
Pretty Printing Xml with JavaScript
Why Is Requestanimationframe Better Than Setinterval or Settimeout
Immediate Function Invocation Syntax
Find and Remove Objects in an Array Based on a Key Value in JavaScript