Search code examples
xmlregexpretty-print

Regex to Indent an XML File


Is it possible to write a REGEX (search replace) that when run on an XML string will output that XML string indented nicely?

If so whats the REGEX :)


Solution

  • Is it possible to write a REGEX (search replace) that when run on an XML string [...anything]

    No.

    Use an XML parser to read the string, then an XML serialiser to write it back out in ‘pretty’ mode.

    Each XML processor has its own options so it depends on platform, but here is the somewhat long-winded way that works on DOM Level 3 LS-compliant implementations:

    input= implementation.createLSInput();
    input.stringData= unprettyxml;
    parser= implementation.createLSParser(implementation.MODE_SYNCHRONOUS, null);
    document= parser.parse(input);
    serializer= implementation.createLSSerializer();
    serializer.domConfig.setParameter("format-pretty-print", true);
    prettyxml= serializer.writeToString(document);