写入xml节点的全部内容而不添加“xmlns =”

时间:2016-04-09 05:53:28

标签: python xml

从我的xml文件中,我想将每个子节点写入一个单独的文件。我为此使用了xml.etree.ElementTree.tostring(child_node)。我已经发现我应该使用.register_namespace()来避免向每个标记添加“ns0:”。但我仍然将“xmlns =”属性添加到我正在保存的每个节点:

以下是示例xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
 <name>ref.kml</name>
 <Style id="normalState">
    <IconStyle><scale>1.0</scale><Icon><href>yt.png</href></Icon></IconStyle>
    <BalloonStyle><text><![CDATA[$[description]]]></text></BalloonStyle>    
 </Style>
</Document>
</kml>

这是我的代码:

#!/usr/bin/env python

import xml.etree.ElementTree as ET

str_ns_url = 'http://earth.google.com/kml/2.1'
ET.register_namespace('', str_ns_url)

kml_file = ET.parse('my.kml')
kml_doc = kml_file.getroot()[0]

ndx = 0
for child in kml_doc:
    ndx+=1
    f = open('node'+str(ndx)+'.txt','w')
    f.write(ET.tostring(child))
    f.close()

这是第一个节点(<name>)的输出:

<name xmlns="http://earth.google.com/kml/2.1">ref.kml</name>

如您所见,xmlns=已添加到代码中。到目前为止,我只发现this SO post,它基本上建议在.tostring()之后手动删除该子字符串。有没有更好的解决方案?也许我应该使用其他东西而不是ElementTree.tostring()

0 个答案:

没有答案
相关问题