字符串 XML 格式化处理(JAVA)

前端之家收集整理的这篇文章主要介绍了字符串 XML 格式化处理(JAVA)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

转换前:<Head><name>wangjj</name><age>23</age></Head>
转换后:

<?xml version="1.0" encoding="gb2312"?>

<Head>
<name>wangjj</name>
<age>23</age>
</Head>

代码:

package com.sun.ATest;

import java.io.StringWriter;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class XmlFormat {
//字符串 XML 格式化处理
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String temp = new XmlFormat().formatXml("<Head><name>wangjj</name><age>23</age></Head>");
System.out.println(temp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

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();

return writer.toString(); } }

猜你在找的XML相关文章