首页 > 其他分享 >Map转xml

Map转xml

时间:2023-08-06 16:04:28浏览次数:35  
标签:xml Map obj strBuilder object instanceof return append

今日问题 小记之

工作中我们有时会遇到map转换xml的需求 今天特意记下 话不多说 直接上代码 使用递归的思路

public static String map2Xml(Map<String, Object> paramMap) {
synchronized (MapUtil.class) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(“\n”);
strBuilder.append(““);
Set objSet = paramMap.keySet();
for (String key : objSet) {
if (key == null) {
continue;
}
strBuilder.append(“\n”);
strBuilder.append(“<”).append(key).append(“>\n”);
Object value = paramMap.get(key);
strBuilder.append(convert(value));
strBuilder.append(“</“).append(key).append(“>”);
}
strBuilder.append(“\n“);
return strBuilder.toString();
}
}
public static String convert(Map map) {
    StringBuilder strBuilder = new StringBuilder();
    for (Object o : map.keySet()) {
        strBuilder.append("<").append(o).append(">");
        strBuilder.append(convert(map.get(o)));
        strBuilder.append("</").append(o).append(">\n");
    }
    return strBuilder.toString();
}

public static String convert(Collection<?> objects) {
    StringBuilder strBuilder = new StringBuilder("\n");
    for (Object obj : objects) {
        strBuilder.append("<").append(obj).append(">");
        strBuilder.append(convert(obj));
        strBuilder.append("</").append(obj).append(">\n");
    }
    return strBuilder.toString();
}

/**
 * 描述:递归进行转换
 * Created by zjw on 2018-12-11 11:21:37
 *
 * @param object
 * @return String
 */
public static String convert(Object object) {
    if (object instanceof Map) {
        return convert((Map)object);
    }
    if (object instanceof Collection) {
        return convert((Collection<?>) object);
    }
    StringBuilder strBuilder = new StringBuilder();
    if (isObject(object)) {
        Class<?> clz = object.getClass();
        Field[] fields = clz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value;
            try {
                value = field.get(object);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                continue;
            }
            strBuilder.append("<").append(fieldName).append("\">");
            if (isObject(value)) {
                strBuilder.append(convert(value));
            } else {
                strBuilder.append(value.toString());
            }
            strBuilder.append("</").append(fieldName).append(">");
        }
    } else if (object == null) {
        strBuilder.append("null");
    } else {
        strBuilder.append(object.toString());
    }
    return strBuilder.toString();
}

/**
 * 描述:判断是否是对象
 * Created by zjw on 2018-12-11 11:20:48
 *
 * @param obj
 * @return boolean
 */
private static boolean isObject(Object obj) {
    if (obj == null) return false;
    if (obj instanceof String) return false;
    if (obj instanceof Integer) return false;
    if (obj instanceof Double) return false;
    if (obj instanceof Float) return false;
    if (obj instanceof Byte) return false;
    if (obj instanceof Long) return false;
    if (obj instanceof Character) return false;
    if (obj instanceof Short) return false;
    return !(obj instanceof Boolean);
}

public static void main(String[] args) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    Map<String, Object> reqParamMap = new HashMap<>();
    Map<String, Object> pubInfoMap = new HashMap<>();
    Map<String, Object> busInfoMap = new HashMap<>();
    reqParamMap.put("PUB_INFO", pubInfoMap);
    reqParamMap.put("BUSI_INFO", busInfoMap);
    pubInfoMap.put("REQ_TIME", sdf.format(new Date()));
    pubInfoMap.put("CHANNLE_ID", "789");
    pubInfoMap.put("REGION_ID", "123");
    pubInfoMap.put("REQ_SERIAL_NO", "20181211");
    pubInfoMap.put("PROCESS_CODE", "TokenCheck");
    busInfoMap.put("TOKEN", "testToken");
    // busInfoMap.put("list", Arrays.asList("abc", "def"));
    System.out.println(GsonUtil.toJson(reqParamMap));
    System.out.println(MapUtil.map2Xml(reqParamMap));
}

标签:xml,Map,obj,strBuilder,object,instanceof,return,append
From: https://blog.51cto.com/u_11906056/6984832

相关文章

  • xml2yolo脚本
    xml2yolo脚本yolo所对应的格式是.txt,其中包含框的类别索引,中心点坐标,boundingboxs的宽,高。importxml.etree.ElementTreeasETimportpickleimportosfromosimportlistdir,getcwdfromos.pathimportjoinimportglobclasses=["crazing","inclusion","pa......
  • 前端学习笔记202306学习笔记第三十八天-手写map2
     ......
  • java202304java学习笔记第六十五天-ssm-声明式控制-基于xml的声明式配置-mybatis的概
      ......
  • 什么是 SAP UI5 XML 视图里的 customData
    下面是XML视图里的代码:<core:FragmentDefinitionxmlns:core="sap.ui.core"xmlns="sap.m"><Column><Texttext="{i18n|sap.suite.ui.generic.template.ListReport|STTA_C_MP_Product>xfld.Rating}"......
  • 开源.NetCore通用工具库Xmtool使用连载 - XML操作篇
    【Github源码】《上一篇》介绍了Xmtool工具库中的发送短信类库,今天我们继续为大家介绍其中的XML操作类库。XML操作是软件开发过程中经常会遇到的情况;包括XML内容的遍历解析,或者特定值内容的查询获取等等。Xmtool工具库提供了一种更方便的方式对Xml进行遍历解析或者对特定节点......
  • Spring源码之XML文件中Bean标签的解析1
    读取XML文件,创建对象xml文件里包含Bean的信息,为了避免多次IO,需要一次性读取xml文件中所有bean信息,加入到Spring工厂。读取配置文件newClassPathResource("applicationContext.xml")ClassPathResource是Spring封装的一个类型;Resource接口:可以读取相关资源文件的内容获得......
  • Mapping iostat to the node exporter’s node_disk_* metrics
    参考:https://www.robustperception.io/mapping-iostat-to-the-node-exporters-node_disk_-metrics/ Thenodeexporterandtoolslikeiostatandsarusethesamecoredata,buthowdotheyrelatetoeachother? Prometheusmetricnamestendtotieprettydirect......
  • python系列教程211——map
    声明:在人工智能技术教学期间,不少学生向我提一些python相关的问题,所以为了让同学们掌握更多扩展知识更好地理解AI技术,我让助理负责分享这套python系列教程,希望能帮到大家!由于这套python教程不是由我所写,所以不如我的AI技术教学风趣幽默,学起来比较枯燥;但它的知识点还是讲到位的了,也值......
  • pom.xml
    打包插件<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>3.2.4</version>......
  • Android开发 Jetpack Compose 与xml的混合开发AndroidView
    前言  JetpackCompose虽然已经逐渐完善,但是其实还是有很多地方未满足需求。比如播放视频、相机预览等等依然需要原来的View。所以目前阶段JetpackCompose与xml的混合开发非常重要。  官方文档地址:https://developer.android.google.cn/jetpack/compose/migrate/interopera......