java - 如何使用正则表达式从 XML 中提取标签名称
问题描述
我有一个我正在尝试解决的问题。我有两种格式的 xml 请求
<?xml version="1.0" encoding="UTF-8"?>
<Request xmlns="urn:x-facebook-com:DEF.plan.services.test">
<OneRequest>
<page_number>1</page_number>
<page_size>25</page_size>
<origin>TEST</origin>
<item_name/>
</OneRequest>
</Request>
<?xml version="1.0" encoding="UTF-8"?>
<Request xmlns="urn:x-google-com:ABC.plan.services.plans">
<SecondRequest/>
</Request>
在这两种情况下,我都想提取在<Request>
. 即OneRequest
和SecondRequest
(这些将是动态的,并且有 100 个)。我尝试使用正则表达式,但没有得到我想要的。任何意见或建议将不胜感激。
也确实看到了有关 xml 解析器的帖子,但对于我基本上想要的只是之后的第一个标签来说,这似乎有点过头了<Request>
我的尝试
String[] requestTags = requestBody.split("</");
String requestName = requestTags[requestTags.length-2].replaceAll("[^a-zA-Z0-9]",
在第一种上不是最好的,但在第二种上完全搞砸了
解决方案
您基本上只需要\s
正则表达式中的选项即可实现此目的:
使用此正则表达式,并从tagname
组中获取值:
<Request .*?>\s*<(?<tagname>.*?)>
推荐阅读
- python - 如何在二进制数中找到连续 1 的 GROUP 数量
- rust - 如何为泛型实现扩展特征
- java - 探索读取和转换字符串格式所需的 Java 流
- python - 使用vector2时我在pygame中遇到错误
- parallel-processing - Julia 中的并行计算
- android - 本地文件系统上不存在 Android SDK 根文件夹“platform-tools”
- javascript - 如何删除重复的下拉菜单
- prolog - SWI-Prolog 找不到 pce 库
- reactjs - 从 cloudinary url 下载图像
- 3d - 加入 2 个对象不会使它们成为 1 个网格