Java 格式化xml字符串

来源:互联网 发布:线性同余法 PHP 编辑:程序博客网 时间:2024/05/22 14:36

Java 格式化xml字符串


基础思路

xml格式报文采用标签对的形式来表示,通常的结构为value,其中,value值可以为嵌套的xml报文。
先假设这样一个xml字符串:

<xml><a>1</a><b><c>2</c></b><d>3</d></xml>

格式化后的样式为:

<xml>    <a>1</a>    <b>        <c>2</c>    </b>    <d>3</d></xml>

本文的解决思路为:

  • 读取xml报文的第一个标签,读取这个标签的内容,记作inside,和这个标签外的报文记作outside。
  • 依次对inside和outside作为xml报文对其进行步骤1的处理。如果检测到inside不是xml报文或outside为空,则不做处理。

代码实现

主体代码:

private static String formatXml(String message, int depth) {    String format = ""; //格式化的xml报文    String firstTag = getFirstTag(message);    String inside = getInsideContent(firstTag, message);    String outside = getOutsideContent(firstTag, message);    String insideTag = getFirstTag(inside); //根据是否含有第一个标签来获取字符串是否是xml报文格式,这个的判断逻辑并不严谨    //对于inside是xml报文的情况下,当前标签的结束标记需要另起一行    if (insideTag == null) {        format = "\r\n" + indent(depth) + "<"             + firstTag + ">" + inside + "</" + firstTag + ">";    } else {        format = "\r\n" + indent(depth) + "<"             + firstTag + ">" + formatXml(inside, depth + 1)            + indent(depth) + "</" + firstTag + ">";    }    String outsideTag = getFirstTag(outside);    if (outsideTag != null) {        format += indent(depth) + formatXml(outside, depth);    } else {        format += "\r\n";    }    return format;}

以下函数实现比较容易,就不贴代码出来了:

  • String getFirstTag(String content)
    content:xml报文
    return:获取xml报文的第一个标签,没有则返回为空

  • String getInsideContent(String tag, String content)
    tag:标签
    content:xml报文
    return:获取该标签下的value值

  • String getOutsideContent(String tag, String content)
    tag:标签
    content:xml报文
    return:获取该标签外的报文

  • String indent(int depth)
    depth:报文深度
    return:获取当前标签需要的空格字符串

测试

测试代码:
formatXml(content, 0)
测试数据:

<books><book><author>Jack Herrington</author><title>PHP Hacks</title><publisher>O'Reilly</publisher></book><book><author>王小为</author><title>深入在线工具</title><publisher>aTool.org组织</publisher></book></books>

测试截图:
这里写图片描述

项目地址

项目地址