美化在 xml 中添加额外的行

prettify adding extra lines in xml

我正在使用 Prettify 使我的 XML 文件可读。我正在将一些新信息添加到一个删除的 XML 文件中,但是当我将它保存到一个文件中时,我在两行之间得到了额外的行。有没有办法删除这些行?下面是我使用的代码

import xml.etree.ElementTree as xml
import xml.dom.minidom as  minidom
from lxml import etree

def prettify(elem):
    rough_string = xml.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")


cid = "[123,123,123,123,123]"

doc = xml.parse('test.xml')
root = doc.getroot()

root.getchildren().index(root.find('card'))

e = xml.Element('card')
e.set('id', cid)
n = xml.SubElement(e, "name")
n.text = "FOLDER"
r = xml.SubElement(e, "red")
r.text = "FILE.AVI"
g = xml.SubElement(e, "green")
g.text = "FILE.AVI"
b = xml.SubElement(e, "blue")
b.text = "FILE.AVI"

root.insert(0, e)

doc2 =  prettify(root)

with open("testnew.xml", "w") as f:
    f.write(doc2)

下面是我在文件中得到的内容

<data>


    <card id="[123,123,123,123,123]">
            <name>FOLDER</name>
            <red>FILE.AVI</red>
            <green>FILE.AVI</green>
            <blue>FILE.AVI</blue>
    </card>
    <card id="[000,000,000,000,000]">


            <name>Colours</name>


            <red>/media/usb/cow.avi</red>


            <green>/media/usb/pig.avi</green>


            <blue>/media/usb/cat.avi</blue>


    </card>


</data>

输入文件 "test.xml" 看起来像

<data>
   <card id="[000,000,000,000,000]">
        <name>Colours</name>
        <red>/media/usb/cow.avi</red>
        <green>/media/usb/pig.avi</green>
        <blue>/media/usb/cat.avi</blue>
   </card>
</data>

新添加的内容打印正常。删除现有文本的任何 "prettification" 即可解决问题

添加

for elem in root.iter('*'):
    if elem == e:
        print "Added XML node does not need to be stripped"
        continue
    if elem.text is not None:
        elem.text = elem.text.strip()
    if elem.tail is not None:
        elem.tail = elem.tail.strip()

调用前

 doc2 =  prettify(root)

相关回答:Python how to strip white-spaces from xml text nodes