【发布时间】:2016-04-09 05:53:27
【问题描述】:
从我的 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()?
【问题讨论】: