您当前的位置: 首页 >  Java

杨林伟

暂无认证

  • 3浏览

    0关注

    3337博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java实现XML格式化

杨林伟 发布时间:2022-07-28 14:38:56 ,浏览量:3

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 = "\n" +
                "\n" +
                "\n" +
                "yarn.acl.enabletrueyarn.admin.acl*\n";


        System.out.println(prettyPrintByTransformer(xml, 2, false));

    }
}

在这里插入图片描述

关注
打赏
1662376985
查看更多评论
立即登录/注册

微信扫码登录

0.0604s