Wiremock:如何匹配URL中指定XML标签内字符串的请求
基于URL中XML片段的Zipcode标签内容匹配请求
步骤拆解
1. 解码URL中的XML参数
你提供的URL里,XML参数经过了URL编码(比如<对应<),必须先将这部分解码为正常的XML字符串,才能处理标签内容。
2. 提取Zipcode标签内的内容
有两种实用方式:
- 正则表达式:用
/<Zipcode>(.*?)<\/Zipcode>/匹配模式,直接捕获标签中间的内容;如果需要兼容大小写,可添加忽略大小写的修饰符。 - XML解析器:若XML结构规范,使用专业的XML解析工具(比如Python的
xml.etree.ElementTree、Java的DOM解析器)定位Zipcode节点并获取文本内容,这种方式比正则更稳定,能避免XML结构微调导致的匹配失败。
3. 忽略其他字段完成匹配
拿到Zipcode的内容后,直接与目标值(比如示例中的89898)对比即可,完全无需关注其他字段的内容。
实操示例(Python)
import urllib.parse import re # 原始URL raw_url = "https://localhost:8080/Test.dll?API=GetData&XML=<GetDataRequest><USERID='TEST1'><Address ID='0'><Address1>500</Address1><Address2>TestAddress2</Address2><City>TestCity</City><State>FL</State><Zipcode>89898</Zipcode></Address></GetDataRequest>" # 解析URL并提取XML参数 parsed_url = urllib.parse.urlparse(raw_url) query_params = urllib.parse.parse_qs(parsed_url.query) encoded_xml = query_params['XML'][0] # 解码为正常XML字符串 decoded_xml = urllib.parse.unquote(encoded_xml) # 提取Zipcode内容并匹配 zipcode_match = re.search(r'<Zipcode>(.*?)</Zipcode>', decoded_xml) if zipcode_match: target_zipcode = "89898" if zipcode_match.group(1) == target_zipcode: print("请求匹配成功") # 若需要提取示例中的TestAddress2,可额外处理 address2_match = re.search(r'<Address2>(.*?)</Address2>', decoded_xml) if address2_match: print(f"提取到Address2内容:{address2_match.group(1)}") else: print("Zipcode不匹配,请求过滤") else: print("URL中未找到Zipcode标签")
内容的提问来源于stack exchange,提问作者Rtn9
相关产品推荐
相关产品推荐

