根据标签名递归读取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>
相关推荐
坐吃山猪7 分钟前
SpringBoot01-配置文件
java·开发语言
晚风(●•σ )9 分钟前
C++语言程序设计——06 字符串
开发语言·c++
我叫汪枫31 分钟前
《Java餐厅的待客之道:BIO, NIO, AIO三种服务模式的进化》
java·开发语言·nio
Nicole-----32 分钟前
Python - Union联合类型注解
开发语言·python
晚云与城35 分钟前
今日分享:C++ -- list 容器
开发语言·c++
yaoxtao39 分钟前
java.nio.file.InvalidPathException异常
java·linux·ubuntu
兰雪簪轩1 小时前
分布式通信平台测试报告
开发语言·网络·c++·网络协议·测试报告
FPGAI2 小时前
Qt编程之信号与槽
开发语言·qt
Swift社区2 小时前
从 JDK 1.8 切换到 JDK 21 时遇到 NoProviderFoundException 该如何解决?
java·开发语言
0wioiw03 小时前
Go基础(④指针)
开发语言·后端·golang