用Python编写易读的XML

dut*_*tch 1 python xml

除了创建一个方法以外,还有其他方法可以使用易于阅读的python编写XML吗?xMLFile.write(xmlDom.toxml())确实创建了正确的xml,但读取它们非常困难.我试过toprettyxml,但似乎并没有做太多.例如,以下是我认为人类可读的xml:

<myroot>
    <ent1
        att1="val1"
        att2="val2"
        att3="val3"
    />
    <ent2>
        <ent3
            att1="val1"
            att2="val2"
        />
    </ent2>
</myroot>
Run Code Online (Sandbox Code Playgroud)

以下响应中的解决方案摘要:
1)如果您只是需要偶尔读取它以进行调试,那么在编写时使用xmllint或xml编辑器来读取它而不是格式化xml.或者
2)使用像Beautiful Soup这样的图书馆.或
3)编写自己的方法

Wal*_*ter 6

print lxml.etree.tostring(root_node, pretty_print=True)
Run Code Online (Sandbox Code Playgroud)