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

工具类:

  /**
   * 根据标签名递归读取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;
  }

测试:

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) {
        // ...
    }
}

输出:

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>

相关推荐

  1. 根据标签读取xml字符串element

    2024-05-25 18:11:14       9 阅读
  2. 实现字符串长度的计算

    2024-05-25 18:11:14       14 阅读
  3. pom.xmlresouces标签

    2024-05-25 18:11:14       37 阅读
  4. 通过文章id查询所有评论(xml

    2024-05-25 18:11:14       18 阅读
  5. 读取文件夹下的所有文件

    2024-05-25 18:11:14       28 阅读
  6. 算法 分析json字符串,自制简易表达式

    2024-05-25 18:11:14       20 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-25 18:11:14       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-25 18:11:14       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-25 18:11:14       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-25 18:11:14       18 阅读

热门阅读

  1. 网络协议——有状态协议和无状态协议

    2024-05-25 18:11:14       9 阅读
  2. C#拼接xml

    2024-05-25 18:11:14       10 阅读
  3. xmlhttp中withcredential用法

    2024-05-25 18:11:14       11 阅读
  4. 使用HTTP客户端在Python中进行网页抓取——笔记

    2024-05-25 18:11:14       14 阅读
  5. Vue2常用的组件通信方式有几种

    2024-05-25 18:11:14       14 阅读
  6. STL源码看书笔记(1)——代码解析

    2024-05-25 18:11:14       9 阅读
  7. Qt TreeWidget详细说明

    2024-05-25 18:11:14       12 阅读
  8. Golang:使用net/http实现一个简易的http服务器

    2024-05-25 18:11:14       11 阅读
  9. Go 实现程序优雅退出

    2024-05-25 18:11:14       8 阅读