You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python正则区分列表模式?无包实现XML转JSON遇正则问题

嘿,我来帮你解决这两个问题哈!先从你遇到的XML转JSON的具体问题说起,再讲正则区分列表模式的思路~

一、解决XML转JSON时的元素匹配问题

你之前的正则x = re.compile("<Description>(.+?)</Description>\n")有两个小问题:

  1. 正则里的.默认不匹配换行符,所以遇到<Description>Test\n Data</Description>这种带换行的内容就抓不到;
  2. 结尾的\n限制太死,不是所有标签后都会紧跟换行,导致部分元素匹配失败。

调整后的正则可以完美适配带换行的内容,两种方案任你选:

import re

# 方案1:用[\s\S]代替.,匹配所有空白和非空白字符(包括换行)
desc_pattern = re.compile(r"<Description>([\s\S]+?)</Description>")

# 方案2:用re.DOTALL(或re.S)标志,让.匹配换行符
desc_pattern = re.compile(r"<Description>(.+?)</Description>", re.DOTALL)

# 测试你的示例XML内容
xml_sample = """<Description>TestData</Description>
 Data</Description>
 <Description>Test
  Some multi-line text</Description>"""

# 获取所有匹配的内容
all_descriptions = desc_pattern.findall(xml_sample)
print(all_descriptions)
# 输出:['TestData', ' Data', 'Test\n  Some multi-line text']

拿到这些匹配结果后,你就可以按原计划转成列表、嵌套字典,最后用json.dumps()生成JSON啦。

二、用Python正则区分列表模式

这里的“列表模式”应该是指XML中重复出现的相同标签元素(比如多个),要区分是单个元素还是多个元素组成的列表,步骤很简单:

  1. 用正则的findall()方法获取所有匹配项,它本身返回的就是一个列表;
  2. 根据列表长度判断处理逻辑:
    • 如果只有1个匹配结果,转字典时作为单个值;
    • 如果有多个结果,直接把列表赋值给对应的键。

示例代码如下:

import re
import json

# 示例XML内容
xml_content = """<Root>
    <Description>First content</Description>
    <Description>Second content with\nline break</Description>
    <Description>Third content</Description>
</Root>"""

# 匹配所有Description元素
desc_pattern = re.compile(r"<Description>(.+?)</Description>", re.DOTALL)
descriptions = desc_pattern.findall(xml_content)

# 构建嵌套字典
result = {}
if len(descriptions) == 1:
    result["Description"] = descriptions[0]
else:
    result["Description"] = descriptions

# 转为JSON
json_output = json.dumps(result, indent=2)
print(json_output)

输出的JSON会自动把多个Description处理成列表:

{
  "Description": [
    "First content",
    "Second content with\nline break",
    "Third content"
  ]
}

小提醒:正则只适合处理结构简单的XML,如果遇到带属性、深层嵌套的复杂XML,手动处理会很麻烦,但既然你明确要求不用Python包,这个方法完全够用啦~

内容的提问来源于stack exchange,提问作者Krishnendu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:18:26