首页 > 解决方案 > 如何使用正则表达式从 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>. 即OneRequestSecondRequest(这些将是动态的,并且有 100 个)。我尝试使用正则表达式,但没有得到我想要的。任何意见或建议将不胜感激。

也确实看到了有关 xml 解析器的帖子,但对于我基本上想要的只是之后的第一个标签来说,这似乎有点过头了<Request>

我的尝试

String[] requestTags = requestBody.split("</");
String requestName = requestTags[requestTags.length-2].replaceAll("[^a-zA-Z0-9]",

在第一种上不是最好的,但在第二种上完全搞砸了

标签: javaregex

解决方案


您基本上只需要\s正则表达式中的选项即可实现此目的:

使用此正则表达式,并从tagname组中获取值:

<Request .*?>\s*<(?<tagname>.*?)>

请参阅 regex101 工作示例


推荐阅读