Python将xml转换为json需要类似字节的对象

2024-09-21 03:15:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<Main xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns="http://cnig.gouv.fr/pcrs" gml:id="PlanCorpsRueSimplifie.1" version="2.0">
    <gml:boundedBy>
    </gml:boundedBy>
    <featureMember>
        <EmpriseEchangePCRS gml:id="EmpriseEchangePCRS.12189894">
            <datePublication>2020-05-13</datePublication>
            <type>Cellules</type>
            <geometrie>
                <gml:MultiSurface gml:id="EmpriseEchangePCRS.12189894-0" srsName="EPSG:3944" srsDimension="3">
                    <gml:surfaceMember>
                        <gml:Surface gml:id="EmpriseEchangePCRS.12189894-1">
                            <gml:patches>
                            </gml:patches>
                        </gml:Surface>

我想把这个文件转换成json文件。 我试过了,但我总是犯同样的错误:

import xmltodict
import xml.etree.ElementTree as ET

root = ET.fromstring(open('JeuxTestv2.gml').read())

print(xmltodict.parse(root)['Main'])

错误:

Traceback (most recent call last):
  File "C:\Users\xmltodict.py", line 6, in <module>
    print(xmltodict.parse(root)['Main'])
  File "C:\Users\xmltodict.py", line 327, in parse
    parser.Parse(xml_input, True)
TypeError: a bytes-like object is required, not 'xml.etree.ElementTree.Element'

Tags: 文件orgidhttpparsemainversionwww
1条回答
网友
1楼 · 发布于 2024-09-21 03:15:00

我正在使用Python 3.7.6

当我尝试时,ET.fromstring()将解析已经以字符串格式表示的XML

import os
import xml.etree.ElementTree as et
xml_doc_path = os.path.abspath(r"C:\dir1\path\to\file\example.xml")
root = et.fromstring(xml_doc_path)
print(root)

此示例将显示以下错误

xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 2

我使用ET.tostring()生成XML数据的字符串表示,它可以用作xmltodict.parse()的有效参数Click这里是ET.tostring()文档

下面的代码将解析XML文件并生成JSON文件。我使用了自己的XML示例。确保所有XML标记都已正确关闭

XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <element1 attribute1 = 'first attribute'>
    </element1>
    <element2 attribute1 = 'second attribute'>
        some data
    </element2>
</root>

PYTHON代码:

import os
import xmltodict
import xml.etree.ElementTree as et
import json
xml_doc_path = os.path.abspath(r"C:\directory\path\to\file\example.xml")

xml_tree = et.parse(xml_doc_path)

root = xml_tree.getroot()
#set encoding to and method proper
to_string  = et.tostring(root, encoding='UTF-8', method='xml')

xml_to_dict = xmltodict.parse(to_string)

with open("json_data.json", "w",) as json_file:
    json.dump(xml_to_dict, json_file, indent = 2)

输出: 上述代码将创建以下JSON文件:

{
  "root": {
    "element1": {
      "@attribute1": "first attribute"
    },
    "element2": {
      "@attribute1": "second attribute",
      "#text": "some data"
    }
  }
}

相关问题 更多 >

    热门问题