Json转换为带有属性而不是元素的XML



我需要解析一个Json:

{
"operacion": "ingresarOrdenBilateral",
"agente" : "0062",
"comitente" : 7211,
"fechaOrigen" : "2021-09-23T16:51:27.873-03:00",
"tipo" : "V",
"instrumento" : "GD30",
"tipoVenc" : "24",
"precio" : "100000000",
"cantidad" : "1",
"idOrigen" : 10699570
"ejecucion" : "SINCRONICA"
}

到这个XML:

<ingresarOrdenBilateral 
agente="150" idOrigen="10039" fechaOrigen="2018-08-16T11:28:08.495-03:00" tipo="V" 
instrumento="AA17" tipoVenc="24" cantidad="1000000" precio="1625" formaOp="C" 
ejecucion="SINCRONICA"/> 

我已经尝试了库xmltodict和dicttoxml,但我无法使用属性而不是元素获得XML。我还认为XML格式不标准。

谢谢!

可以用内置的xml.etree.ElementTree:

一行完成
import xml.etree.ElementTree as ET
data = {
"operacion": "ingresarOrdenBilateral",
"agente": "0062",
"comitente": 7211,
"fechaOrigen": "2021-09-23T16:51:27.873-03:00",
"tipo": "V",
"instrumento": "GD30",
"tipoVenc": "24",
"precio": "100000000",
"cantidad": "1",
"idOrigen": 10699570,
"ejecucion": "SINCRONICA"
}
ET.dump(ET.Element(data.pop("operacion"), {k: str(v) for k, v in data.items()}))

输出:

<ingresarOrdenBilateral agente="0062" comitente="7211" fechaOrigen="2021-09-23T16:51:27.873-03:00" tipo="V" instrumento="GD30" tipoVenc="24" precio="100000000" cantidad="1" idOrigen="10699570" ejecucion="SINCRONICA" />

乌利希期刊指南。假设你从文件或服务器加载这个JSON数据,有可能传递str()json.load()/json.loads()/requests.Response.json()parse_int参数。它将强制将int字段解析为str,因此我们可以省略我在上面代码中使用的字典推导:

import json
import xml.etree.ElementTree as ET
str_data = '''{
"operacion": "ingresarOrdenBilateral",
"agente": "0062",
"comitente": 7211,
"fechaOrigen": "2021-09-23T16:51:27.873-03:00",
"tipo": "V",
"instrumento": "GD30",
"tipoVenc": "24",
"precio": "100000000",
"cantidad": "1",
"idOrigen": 10699570,
"ejecucion": "SINCRONICA"
}'''
data = json.loads(str_data, parse_int=str)
ET.dump(ET.Element(data.pop("operacion"), data))

还有parse_floatparse_constant,你可以用同样的方式使用(如果需要,ofc)

首先,使用属性而不是子元素是这种结构的完全标准。它可能不像使用子元素那么常见,但它并不罕见,当然也不是非标准的。

其次,JSON和XML之间的标准现成转换器从来没有给您足够的控制来生成您想要的目标结构。如果需要特定的XML格式,则必须准备对结果进行转换,这通常很容易用XSLT实现。

如果你使用XSLT 3.0,那么你可以在一个样式表内完成json到xml的转换和后续的转换;但除此之外,使用您最喜欢的库转换器,然后使用XSLT(1.0+)转换就足够简单了。您会发现很多将XML元素转换为属性的样式表示例。

如果XML是简单的下面的代码可以做这项工作

data = {
"operacion": "ingresarOrdenBilateral",
"agente" : "0062",
"comitente" : 7211,
"fechaOrigen" : "2021-09-23T16:51:27.873-03:00",
"tipo" : "V",
"instrumento" : "GD30",
"tipoVenc" : "24",
"precio" : "100000000",
"cantidad" : "1",
"idOrigen" : 10699570,
"ejecucion" : "SINCRONICA"
}
xml = '<root>' + ' '.join(f'"{k}"="{v}"' for k,v in data.items()) + '</root>'
print(xml)

输出
<?xml version="1.0" encoding="UTF-8"?>
<root>"operacion"="ingresarOrdenBilateral" "agente"="0062" "comitente"="7211" "fechaOrigen"="2021-09-23T16:51:27.873-03:00" "tipo"="V" "instrumento"="GD30" "tipoVenc"="24" "precio"="100000000" "cantidad"="1" "idOrigen"="10699570" "ejecucion"="SINCRONICA"</root>

最新更新