【问题标题】:Converting xml file into json dump python将xml文件转换为json转储python
【发布时间】:2014-12-15 20:54:21
【问题描述】:

您好,我想将 xml 文件解析为 json 转储。已经试过了:

for i in cNodes[0].getElementsByTagName("person"):
        self.userName = i.getElementsByTagName("login")[0].childNodes[0].toxml()
        self.userPassword = i.getElementsByTagName("password")[0].childNodes[0].toxml()
        self.userNick = i.getElementsByTagName("nick")[0].childNodes[0].toxml()

但我想使用 for 循环以 title:value 格式获取标题和值。

<user>
<person>
    <nick>Gamer</nick>
    <login>1</login>
    <password>tajne</password>
</person>
<properties>
    <fullHp>100</fullHp>
    <currentHp>25</currentHp>
    <fullMana>200</fullMana>
    <currentMana>124</currentMana>
    <premiumAcc>1</premiumAcc>
</properties>

这是我的 xml 格式。

【问题讨论】:

    标签: python xml json


    【解决方案1】:

    不要重新发明轮子(“minidom”无论如何都不会有趣),使用xmltodict

    import xmltodict
    
    data = """
    <user>
        <person>
            <nick>Gamer</nick>
            <login>1</login>
            <password>tajne</password>
        </person>
        <properties>
            <fullHp>100</fullHp>
            <currentHp>25</currentHp>
            <fullMana>200</fullMana>
            <currentMana>124</currentMana>
            <premiumAcc>1</premiumAcc>
        </properties>
    </user>"""
    
    print xmltodict.parse(data)
    

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 1970-01-01
      • 2017-06-18
      • 2023-03-09
      • 2011-09-21
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多