XML与JSON双向转换及指定XML文件的技术处理请求
Hey there! Let's tackle this XML ↔ JSON bidirectional conversion problem, especially for your specific XML file with embedded schema. I'll walk you through practical, code-based solutions using Python—super straightforward and widely used in real-world projects.
Prerequisite: Install Required Library
We'll use the xmltodict library—it's perfect for handling XML with complex structures (like your schema-included file) and plays nicely with Python's built-in json module. Install it via pip:
pip install xmltodict
1. Convert XML to JSON
Your XML includes a schema definition and namespaces (xs, msdata), so we'll use xmltodict's namespace handling to preserve all structure correctly. Here's the code:
import xmltodict import json # Your target XML content (expanded from your truncated snippet for complete example) xml_content = '''<?xml version="1.0" standalone="yes"?> <NewDataSet> <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="Table1"> <xs:complexType> <xs:sequence> <xs:element name="MA_ID" type="xs:string" minOccurs="0"/> <xs:element name="MA_NAME" type="xs:string" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <Table1> <MA_ID>MA001</MA_ID> <MA_NAME>Sample Item</MA_NAME> </Table1> </NewDataSet>''' # Parse XML to ordered dictionary, handle namespaces properly xml_dict = xmltodict.parse(xml_content, process_namespaces=True) # Convert dict to human-readable JSON string json_content = json.dumps(xml_dict, indent=4) # Output or save the result print("XML converted to JSON:\n") print(json_content) # To save to file: # with open('output.json', 'w') as f: # f.write(json_content)
Key Notes for XML → JSON:
process_namespaces=Trueensures thexs:andmsdata:prefixes and their URIs are retained instead of being dropped.- The resulting JSON preserves the full structure, including the schema definition and data rows like
<Table1>.
2. Convert JSON Back to XML
To reverse the process, we'll take the JSON string (or a Python dict) and convert it back to well-formed XML, matching your original file's structure and declarations:
import xmltodict import json # Use the JSON content from the previous step (or load from a file) json_content = '''{ "NewDataSet": { "xs:schema": { "@id": "NewDataSet", "@xmlns:xs": "http://www.w3.org/2001/XMLSchema", "@xmlns:msdata": "urn:schemas-microsoft-com:xml-msdata", "xs:element": { "@name": "NewDataSet", "@msdata:IsDataSet": "true", "@msdata:UseCurrentLocale": "true", "xs:complexType": { "xs:choice": { "@minOccurs": "0", "@maxOccurs": "unbounded", "xs:element": { "@name": "Table1", "xs:complexType": { "xs:sequence": { "xs:element": [ { "@name": "MA_ID", "@type": "xs:string", "@minOccurs": "0" }, { "@name": "MA_NAME", "@type": "xs:string", "@minOccurs": "0" } ] } } } } } } }, "Table1": { "MA_ID": "MA001", "MA_NAME": "Sample Item" } } }''' # Convert JSON to Python dict json_dict = json.loads(json_content) # Convert dict back to properly formatted XML xml_content = xmltodict.unparse( json_dict, pretty=True, encoding='utf-8', xml_declaration='<?xml version="1.0" standalone="yes"?>' ) # Output or save the result print("\nJSON converted back to XML:\n") print(xml_content.decode('utf-8')) # To save to file: # with open('output.xml', 'wb') as f: # f.write(xml_content)
Key Notes for JSON → XML:
pretty=Trueadds indentation to make the XML human-readable.- The
xml_declarationparameter ensures the output matches your original XML's standalone attribute. - All original namespaces and schema details are preserved exactly.
Additional Customization Tips
- If you only need to convert the data rows (not the schema), filter the parsed XML dict first:
data_only_dict = xml_dict['NewDataSet']['Table1'] - Use
attr_prefix=''inxmltodict.parse()if you don't want attribute keys to start with@in the JSON output (note: this can cause conflicts if elements and attributes share the same name).
内容的提问来源于stack exchange,提问作者jimbo R

