---
title: "将xml格式的字符串进行格式化输出"
author: "javaz"
date: "2010-05-11T15:08:24Z"
tags: ["XML"]
categories: ["编程语言"]
slug: "xml"
draft: false
lastmod: "2010-05-12T13:37:47Z"
id: 663950
url: "https://javaz.iteye.com/blog/663950"
---

```
	public static String formatXml(String str) throws Exception{		
		Document document = null;
		document = DocumentHelper.parseText(str);
		//格式化输出格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("gb2312");
		StringWriter writer = new StringWriter();
		//格式化输出流
		XMLWriter xmlWriter = new XMLWriter(writer,format);
		//将document写入到输出流
		xmlWriter.write(document);
		xmlWriter.close();
		//输出到控制台
		System.out.println(writer.toString());
		return writer.toString();
	}
```

   可根据需要更改编码。