<?xml version="1.0"?>
<purchaseOrder orderDate="1999-10-20" xmlns="http://www.example.com/PO">
<shipTo country="US">
<name>Alice Smith</name>
<street>123 Maple Street</street>
<city>Mill Valley</city>
<state>CA</state>
<zip>90952</zip>
</shipTo>
<billTo country="US">
<name>Robert Smith</name>
<street>8 Oak Avenue</street>
<city>Old Town</city>
<state>PA</state>
<zip>95819</zip>
</billTo>
<comment>Hurry, my lawn is going wild!</comment>
<items>
<item partNum="872-AA">
<productName>Lawnmower</productName>
<quantity>1</quantity>
<USPrice>148.95</USPrice>
<comment>Confirm this is electric</comment>
</item>
<item partNum="926-AA">
<productName>Baby Monitor</productName>
<quantity>1</quantity>
<USPrice>39.98</USPrice>
<shipDate>1999-05-21</shipDate>
</item>
</items>
</purchaseOrder>
{
"purchaseOrder": {
"$": {
"orderDate": "1999-10-20",
"xmlns": "http://www.example.com/PO"
},
"shipTo": [
{
"$": {
"country": "US"
},
"name": [
"Alice Smith"
],
"street": [
"123 Maple Street"
],
"city": [
"Mill Valley"
],
"state": [
"CA"
],
"zip": [
"90952"
]
}
],
"billTo": [
{
"$": {
"country": "US"
},
"name": [
"Robert Smith"
],
"street": [
"8 Oak Avenue"
],
"city": [
"Old Town"
],
"state": [
"PA"
],
"zip": [
"95819"
]
}
],
"comment": [
"Hurry, my lawn is going wild!"
],
"items": [
{
"item": [
{
"$": {
"partNum": "872-AA"
},
"productName": [
"Lawnmower"
],
"quantity": [
"1"
],
"USPrice": [
"148.95"
],
"comment": [
"Confirm this is electric"
]
},
{
"$": {
"partNum": "926-AA"
},
"productName": [
"Baby Monitor"
],
"quantity": [
"1"
],
"USPrice": [
"39.98"
],
"shipDate": [
"1999-05-21"
]
}
]
}
]
}
}
{
"purchaseOrder": {
"$": {
"orderDate": "1999-10-20T00:00:00.000Z"
},
"shipTo": {
"$": {
"country": "US"
},
"name": "Alice Smith",
"street": "123 Maple Street",
"city": "Mill Valley",
"state": "CA",
"zip": 90952
},
"billTo": {
"$": {
"country": "US"
},
"name": "Robert Smith",
"street": "8 Oak Avenue",
"city": "Old Town",
"state": "PA",
"zip": 95819
},
"comment": "Hurry, my lawn is going wild!",
"items": {
"item": [
{
"$": {
"partNum": "872-AA"
},
"productName": "Lawnmower",
"quantity": 1,
"USPrice": 148.95,
"comment": "Confirm this is electric"
},
{
"$": {
"partNum": "926-AA"
},
"productName": "Baby Monitor",
"quantity": 1,
"USPrice": 39.98,
"shipDate": "1999-05-21T00:00:00.000Z"
}
]
}
}
}
xmlschema
,可以轻松地完成这个任务。to_dict
方法。import xmlschema
import simplejson as json
my_schema = xmlschema.XMLSchema("../shiporder.xsd")
obj = my_schema.to_dict('../shiporder.xml')
# in case you want to save the json in a file
json.dumps(obj)
item
,并查看模式如何保留数组类型。数字类型在转换为json后也会被保留。xmlschema
或者simplejson
依赖于Counter
,而Counter
只在Python 2.7中可用。然而,xmlschema
在Python 2.7上无法安装。 - user358041如果您正在寻找一个Java解决方案。
xjc
的解决方案:使用Java将xml转换为json。使用xjc
,可以从XML模式创建Java类,并使用JAXB工具以不同格式读取和写出数据。
maxOccurs
可以帮助您知道是否应创建数组(如果 maxOccurs
为1,则您不需要数组)。而 type
可以帮助您将其转换为JSON类型。 - Mitar