用Python编写易读的XML

时间:2010-04-22 07:57:07

标签: 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>

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

5 个答案:

答案 0 :(得分:6)

print lxml.etree.tostring(root_node, pretty_print=True)

答案 1 :(得分:1)

如果您使用的是elementalTree,则此代码将起作用。

XMLtext= ET.tostringlist(root)
OutputStr=''
level=-1

for t in XMLtext:

    if t[0]=='<':
            level=level+1
    if t[0:2]=='</':
            #remove the added level because of '<'
        level=level-1

    if t[-1]=='"' or t[0]=='<' or t[-2:]=='/>':
        t="\n"+"    "*level+t 

    if t[-2:]=='/>' or t[level*4+1:level*4+3]=='</': #end of block 
        level=level-1

    if t[-1:]=='>':    
        t=t+'\n'


    OutputStr=OutputStr+t

f = open("test.xml", "w")
f.write(OutputStr)
f.close()

答案 2 :(得分:0)

不幸的是,人类的XML可读性不是设计目标。相反,BeautifulStoneSoup努力美化XML。它并不好,但总比没有好。

答案 3 :(得分:0)

编写自己的格式化xml doc的方法。例如,这将生成示例XML字符串的格式:

rep={" ":" \n",
     "/>":"\n/>"}

outStr=xmlDom.toxml()

for k in rep:
        outStr=outStr.replace(k, rep[k])

答案 4 :(得分:0)

我认为使用python包含电池的最佳方法是在这个答案中给出:https://stackoverflow.com/a/1206856

import xml.dom.minidom

xml = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xml.toprettyxml()