美化在xml

时间:2016-10-13 10:06:22

标签: python xml prettify

我使用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>

输入文件&#34; test.xml&#34;看起来像

<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>

1 个答案:

答案 0 :(得分:0)

添加的新内容正在打印。删除现有文本的任何“美化”解决了问题

添加

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