如何将含属性与文本的XML转换为无__text的JSON?
XML转JSON:替换__text字段为元素名称并保留属性
当你用output writeAttributes=true参数把XML转成JSON时,元素的文本内容会被存到__text字段里,但你需要把这个字段替换成对应元素的名称作为键,同时保留所有属性,全局不能出现__text。
示例
XML输入:
<CustomData> <CustomIdentifier attribute1="value1" attribute2="value2"> test </CustomIdentifier> </CustomData>
期望的JSON输出:
{ "CustomData": { "CustomIdentifier": { "@attribute1": "value1", "@attribute2": "value2", "CustomIdentifier": "test" } } }
解决方案:用Python脚本处理
直接用xmltodict库解析XML,再递归处理字典替换__text字段,步骤如下:
- 先安装依赖:
pip install xmltodict
- 运行以下脚本:
import xmltodict import json def replace_text_key(data, parent_key=None): if isinstance(data, dict): new_dict = {} for key, value in data.items(): if key == '__text': # 把文本内容存到以父元素名称为键的字段里 if parent_key is not None: new_dict[parent_key] = value.strip() else: # 递归处理子节点 processed_value = replace_text_key(value, parent_key=key) new_dict[key] = processed_value return new_dict elif isinstance(data, list): # 处理多个同名称元素的列表场景 return [replace_text_key(item, parent_key=parent_key) for item in data] else: return data # 你的XML内容 xml_content = """ <CustomData> <CustomIdentifier attribute1="value1" attribute2="value2"> test </CustomIdentifier> </CustomData> """ # 解析XML,属性前缀用@ parsed_data = xmltodict.parse(xml_content, attr_prefix='@') # 替换__text字段 processed_data = replace_text_key(parsed_data) # 生成格式化的JSON print(json.dumps(processed_data, indent=2))
说明
xmltodict.parse的attr_prefix='@'参数会让XML属性转成JSON里带@前缀的键,和你要的格式一致。- 递归函数
replace_text_key会遍历整个字典,遇到__text就把文本内容转移到以父元素名称命名的键下,同时删掉__text字段。 - 兼容列表场景(比如多个同名XML元素),保证所有情况都不会出现
__text。
内容的提问来源于stack exchange,提问作者Anonim
相关产品推荐
相关产品推荐

