我对Python和XML世界有点陌生。我非常需要你的帮助,我已经没有时间完成这个项目了!基本上,在将xml文件导入Excel之前,我需要详细说明它。我的XML的结构如下(非常小的摘录):
<?xml version="1.0" encoding="UTF-8"?>
<Application>
<first/>
<second>
<third/>
<third/>
<third/>
</second>
</Application>
我需要做的是解析xml文件(元素树或lxml),并消除<first/>
和<second/>
,以便获得如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<Application>
<third/>
<third/>
<third/>
</Application>
我已经阅读并尝试了我所能找到的所有相关问题,但我所做的只是消除了整个<first/>
元素。
我使用的是Python3.6.2,首选标准库(lxml、元素树)。
提前感谢您的任何帮助!
发布于 2017-10-26 08:38:10
最终任务是删除给定示例中的父级。(应用程序-根,第一,第二节点,第三-内节点)
1)加载xml(并在这里找到您认为是“Application”的节点)
2)获取树的inner_nodes列表(树->节点->内节点)
3)获取所有的inner_nodes(此处的节点名为“third”)
4)移除根的直接子--“应用程序”。
5)将所有inner_nodes附加到根目录中!
yourxmlfile.txt
<?xml version="1.0" encoding="UTF-8"?>\n<Application>\n <first/>\n <second>\n <third/>\n <third/>\n <third/>\n </second>\n</Application>
并且可以通过tree.parse()读取xml文件。
>>> import xml.etree.ElementTree as etree
>>> root=etree.parse('yourxmlfile.xml')
>>> etree.tostring(root)
b'<Application>\n <first />\n <second>\n <third />\n <third />\n <third />\n </second>\n</Application>'
>>> inner_nodes=[node.getchildren() for node in root.getchildren()]
>>> print(inner_nodes)
[[], [<Element 'third' at 0x10c272818>, <Element 'third' at 0x10c2727c8>, <Element 'third' at 0x10c272778>]]
>>> for node in root.getchildren():root.remove(node)
...
>>> etree.tostring(root)
b'<Application>\n </Application>'
>>> [[root.append(c) for c in child] for child in filter(None,inner_nodes)]
[[None, None, None]]
>>> etree.tostring(root)
b'<Application>\n <third />\n <third />\n <third />\n </Application>'
https://stackoverflow.com/questions/46958721
复制