package cn.com.paic.utils;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
/**
* User: ldj
* Date: 2021/11/14
* Time: 23:19
* Description: xml文件格式化工具
*/
public class XmlUtil {
public static String formatXML(String unformattedXml) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(unformattedXml));
final Document document = db.parse(is);
OutputFormat format = new OutputFormat(document);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
Writer out = new StringWriter();
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(document);
return out.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String formatStringAsXml(String strXML) throws Exception {
try {
Document document = null;
document = DocumentHelper.parseText(strXML);
// 格式化输出格式
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(String.valueOf(StandardCharsets.UTF_8));
StringWriter writer = new StringWriter();
// 格式化输出流
XMLWriter xmlWriter = new XMLWriter(writer, format);
// 将document写入到输出流
xmlWriter.write(document);
xmlWriter.close();
return writer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
//将要发送的消息
String xml = "<?xml version=\"1.0\" encoding=\"GB2312\"?>" +
" <softCompany>" +
" <company>MicroSoft</company>" +
" <company>google</company>" +
" <company>Apple</company>" +
" <company>百度</company>" +
" </softCompany>";
//将xml文件格式
String fxml = XmlUtil.formatXML(xml);
System.out.println(fxml);
}
}
xml格式化工具类
于 2021-11-15 13:07:54 首次发布