将 XML 转换为 JSON 或 Avro(在 python 中)

convert XML to JSON or Avro (in python)

我正在尝试将 XML 转换为 JSON 或 python 中的 Avro 模式。

你有什么建议吗?

我已经尝试过这段代码:

    import xmltodict
    import json

    with open('xmlskuska.xml') as fd:
         doc = xmltodict.parse(fd.read())

    app_json = json.dumps(doc)
    print(app_json)

    with open('skuska.txt', 'w') as json_file:
         json.dump(doc, json_file)

问题是我想在转换过程中重命名这些属性名称。 这是我的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
    xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
    xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2">
    <cbc:ID>TOSL108</cbc:ID>
    <cbc:IssueDate>2009-12-15</cbc:IssueDate>
    <cac:OrderReference>
        <cbc:ID>123</cbc:ID>
    </cac:OrderReference>
    <cac:InvoiceLine>
        <cac:Price>
            <cbc:PriceAmount currencyID="EUR">0.75</cbc:PriceAmount>
            <cbc:BaseQuantity unitCode="C62">1</cbc:BaseQuantity>
        </cac:Price>
    </cac:InvoiceLine>
</Invoice>

例如,我想将属性 cbc:ID 重命名为 ID。 您对如何使用漂亮的 JSON 或更好的 Avro 输出进行我想要的转换有什么建议吗??

type(doc) 是有序字典。因此,您可以在将其转换为 json 文件之前修改单个键。例如:

import xmltodict
import json

with open('xmlskuska.xml') as fd:
    doc = xmltodict.parse(fd.read())

# Get the old value for cbc:ID and assign it to ID
doc['Invoice']['ID'] = doc['Invoice'].pop('cbc:ID')

app_json = json.dumps(doc)
print(app_json)

with open('skuska.txt', 'w') as json_file:
    json.dump(doc, json_file)