根据标签名递归读取xml字符串中element

工具类:

java 复制代码
  /**
   * 根据标签名递归读取xml字符串中element
   * 例:
   * String xml =
   * "<req>\n" +
   * "<tag1></tag1>\n" +
   * "<tag2>\n" +
   * "  <tag4></tag4>\n" +
   * "</tag2>\n" +
   * "<tag3></tag3>\n" +
   * "</req>";
   * <p>
   * element(xml) => 获得 req element
   * element(xml, "tag1") => 获得 tag1 element
   * element(xml, "tag2", "tag4") => 获得 tag4 element
   *
   * @param xml
   * @param nodes
   * @return
   */
  public static Element element(String xml, String... nodes) {
    try {
      Document document = DocumentHelper.parseText(xml);
      Element element = document.getRootElement();
      for (String node : nodes) {
        element = element.element(node);
      }
      return element;
    } catch (DocumentException e) {
      e.printStackTrace();
    }

    return null;
  }

测试:

java 复制代码
public class Main {
    public static void main(String[] args) {
        String xmlString = "<books><category name='Fiction'><book id='1'>Harry Potter</book></category></books>";

        // 获取 books 元素
        Element booksElement = element(xmlString);
        System.out.println("Books: " + booksElement.asXML());

        // 获取 category 元素
        Element categoryElement = element(xmlString, "category");
        System.out.println("Category: " + categoryElement.asXML());

        // 获取 book 元素
        Element bookElement = element(xmlString, "category", "book");
        System.out.println("Book: " + bookElement.asXML());
    }

    // 之前的 element 函数
    public static Element element(String xml, String... nodes) {
        // ...
    }
}

输出:

java 复制代码
Books: <books><category name="Fiction"><book id="1">Harry Potter</book></category></books>
Category: <category name="Fiction"><book id="1">Harry Potter</book></category>
Book: <book id="1">Harry Potter</book>
相关推荐
学长毕设4 小时前
基于SpringBoot的实验室资产管理系统
java·spring boot·后端
C^h4 小时前
c++ string
开发语言·c++
raindayinrain5 小时前
c++高性能--原子操作,无锁编程,操作顺序
开发语言·c++·性能优化
学逆向的5 小时前
C++ 合并命名空间
开发语言·c++·网络安全
Zhao-Jichao5 小时前
VS2026 打包 C++ 程序生成 EXE,借助 Installer Project 扩展工具
开发语言·c++
zzu123zsw6 小时前
从臃肿的模板调用到声明式契约:深入 UniHttp 动态代理与多渠道生命周期扩展
java·spring boot·microsoft·unihttp
学逆向的6 小时前
C 局部静态变量
c语言·开发语言·网络安全
大都督会赢的6 小时前
C++第一节课
开发语言·c++
“AI国潮设计-小江”6 小时前
【AIGC实战】Python+Stable Diffusion打造“英歌舞财神”IP,解锁“马到成功”等爆款情绪营销文案设计
开发语言·人工智能·python·prompt·aigc
源码集结号6 小时前
云诊所门诊系统源码,基于SpringBoot+Vue.js架构,支持多租户设计与Docker容器化部署
java·spring boot·源码·医院信息系统·门诊系统·诊所系统