Java可以使用自带的API将XML格式化,直接贴上工具类:
/** * 格式化xml * * @param xmlString xml内容 * @param indent 向前缩进多少空格 * @param ignoreDeclaration 是否忽略描述 * @return 格式化后的xml */
public static String prettyPrintByTransformer(String xmlString, int indent, boolean ignoreDeclaration) {
try {
InputSource src = new InputSource(new StringReader(xmlString));
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ignoreDeclaration ? "yes" : "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
Writer out = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(out));
return out.toString();
} catch (Exception e) {
throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
}
}
测试:
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
public class Test {
public static void main(String[] args) throws TransformerConfigurationException {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"\n" +
"<!--Autogenerated by Cloudera Manager-->\n" +
"<configuration><property><name>yarn.acl.enable</name><value>true</value></property><property><name>yarn.admin.acl</name><value>*</value></property></configuration>\n";
System.out.println(prettyPrintByTransformer(xml, 2, false));
}
}
今天的文章Java实现XML格式化分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/30390.html