Hutool XML工具-XmlUtil遇到标签问题

在处理XML时,Hutool是一个非常实用的Java工具库,它提供了便捷的XML操作方法。

如果你在使用Hutool的XmlUtil工具类时遇到了标签类型问题,可能是因为XML结构复杂或特定标签的处理需求。

我遇到了一个稍复杂的xml结构,如下:

xml 复制代码
<user type="GROUP">
	<user_id>247692d5c9d278af</user_id>
	<name>漳平市菁城街道双拥路304城北小区二期A1栋1单元10楼1001号</name>
	<age>181</age>
</user>
  • hutool包
xml 复制代码
    <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>${hutool.version}</version>
    </dependency>

标签type="GROUP",如果返回记录只有一条的情况下,通过XmlUtil.xmlToMap转换时,返回的是user对象,而不是一个集合!

咋整呢。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

  • 先将XML格式字符串转换为json,将json中符合要求的转换为集合,如下:
java 复制代码
  String returnString = "";
  JSONObject jsonObject = JSONUtil.parseFromXml(returnString);
  //将json中符合要求的转换为集合
  normalizeJson(jsonObject);
  //其他业务处理
  • 检查json中是否需要转为数组的标签,以type="GROUP" 为例,代码如下:
java 复制代码
    /**
     * 转换数组
     *
     * @param json json对象
     */
    private static void normalizeJson(JSONObject json) {
        for (String key : json.keySet()) {
            Object value = json.get(key);

            if (value instanceof JSONObject) {
                // 检查是否需要转为数组
                JSONObject obj = (JSONObject) value;
                if (shouldConvertToArray(obj)) {
                    JSONArray array = new JSONArray();
                    array.add(obj);
                    json.set(key, array);
                } else {
                    normalizeJson(obj);
                }
            } else if (value instanceof JSONArray) {
                // 处理数组中的对象
                JSONArray array = (JSONArray) value;
                for (Object item : array) {
                    if (item instanceof JSONObject) {
                        normalizeJson((JSONObject) item);
                    }
                }
            }
        }
    }

    /**
     * 根据标识判断是否需要转换数组
     *
     * @param obj json对象
     */
    public static boolean shouldConvertToArray(JSONObject obj) {
    // 根据你的业务逻辑判断
    // 例如:特定类型或特定属性
    return obj.containsKey("type") && "GROUP".equals(obj.getStr("type"));
    }

已解决我想要的结果,如果有伙伴有其他方案,可以一起交流下!

相关推荐
执明wa2 小时前
LayoutInflater详解: XML是如何变成View的?
android·xml·开发语言·android studio
IT_Octopus2 天前
一次由 RestTemplate 引发的 Connection reset:被 XML 截胡的请求体
xml·java·spring boot
Dontla2 天前
网站爬虫控制策略介绍(robots.txt、sitemap.xml、x-robots-tag、noindex、nofollow)网站索引
xml·爬虫·dubbo
风起洛阳@不良使3 天前
spring中xml和注解开发的对比
xml·java·spring
Mikowoo0074 天前
批量汇总XML格式的发票信息
xml·python
逃逸线LOF5 天前
xml文件如何加载properties文件(spring容器加载properties文件)
xml
前网易架构师-高司机7 天前
带标注的山体滑坡塌方数据集数据集,识别率78.1%,974张图,支持yolo,coco json,voc xml,文末有模型训练代码
xml·yolo·json·数据集·自然灾害·山体滑坡
程序媛kelly7 天前
.xml / .jrxml 文件怎么打开?OpenFiles 实测预览、编辑、搜索与 AI 摘要排查流程
xml·人工智能·jrxml
潘潘的嵌入式日记8 天前
改完Keil工程文件被缓存覆盖?——uvprojx编辑的进阶四坑
xml·嵌入式·keil·调试·mdk·工程文件
Full Stack Developme8 天前
Flowable XML标签大全
xml