【Hutool】之XML解析

【Hutool】之XML解析

xml字符串解析(属性、文本)

  • 代码
package com.myself;

import cn.hutool.Hutool;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import springfox.documentation.spring.web.json.Json;

import java.util.*;

@Slf4j
@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class ApplicationTest {

    public static void main(String[] args) throws Exception {

       String xmlStr = "" +
               "<Action id=\"1\">\n" +
               "\t<Boy key=\"one\">\n" +
               "\t\t<City id=\"1-1\">北京</City>\n" +
               "\t\t<City id=\"1-2\">上海</City>\n" +
               "\t</Boy>\n" +
               "</Action>";
        //读取xml
        Document document = XmlUtil.readXML(xmlStr);
        //获取根节点element
        Element elementAction =XmlUtil.getRootElement(document);
        //获取根节点element对应属性
        String action_id = elementAction.getAttribute("id");
        //获取指定名称节点element
        Element elementBoy = XmlUtil.getElement(elementAction, "Boy");
        //获取指定名称节点element对应属性
        String boy_key = elementBoy.getAttribute("key");
        //集合式节点
        List<Element> elementCityList = XmlUtil.getElements(elementBoy, "City");
        List<String> cityTextList = new ArrayList<>();
        List<String> cityIdList = new ArrayList<>();
        for (Element element : elementCityList) {
            //属性
            String city_text = element.getTextContent();
            cityTextList.add(city_text);
            //文本
            String city_id = element.getAttribute( "id");
            cityIdList.add(city_id);
        }

        System.out.println(action_id);
        System.out.println(boy_key);
        System.out.println(cityTextList);
        System.out.println(cityIdList);

    }

}

  • 输出结果
1
one
[北京, 上海]
[1-1, 1-2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值