---
title: "Format XML in JAVA"
author: "caiwenhn2008"
date: "2016-01-11T12:23:21Z"
tags: []
categories: ["企业架构"]
slug: "format-xml-in-java"
draft: false
lastmod: "2016-01-11T12:23:21Z"
id: 2269790
url: "https://caerun.iteye.com/blog/2269790"
---

```java

  public static String formatXMLContent(final String message)
    {
        try
        {
            final InputSource src = new InputSource(new StringReader(message));
            final Node document =
                DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();

            final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
            LSOutput lso = impl.createLSOutput();
            lso.setEncoding("UTF-8");

            final LSSerializer writer = impl.createLSSerializer();

            writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            writer.getDomConfig().setParameter("xml-declaration", true);

            StringWriter swr = new StringWriter();
            lso.setCharacterStream(swr);
            writer.write(document, lso);
            return swr.toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return message;
        }
    }

```



more sample: 
<http://kveeresham.blogspot.com/2015/03/format-xml-using-java.html>