【问题标题】:How can I use python to remove xml node如何使用 python 删除 xml 节点
【发布时间】:2015-04-22 06:13:25
【问题描述】:

我想从 xml 文件中删除元素。当我使用 ElementTree 时,我可以从 xml 文件中获取所有元素,但无法获取 xml 语句和注释。 所以如果我使用:

# get xml nodes
tree = ElementTree.pares()
# do filter things ...
# write to files
tree.write(file_path)

我会错过所有的陈述和注释。有没有办法从 *.xml 文件中删除 xml 元素并保留文件中的注释、语句或任何其他内容?

例如来源:

<?xml version="1.0" encoding="utf-8"?>
<!-- I am annotation -->
<string name="name">content</string><string left="left">left things</string>

还有我的目标:

<?xml version="1.0" encoding="utf-8"?>
<!-- I am annotation -->
<string left="left">left things</string>

但是当我使用tree.write(file_path)时,会漏掉注解和语句,变成:

<string left="left">left things</string>

【问题讨论】:

  • 您想删除 nodes 还是只删除 tags?节点是一个带有其内容的标签。
  • 对不起,我是说元素。我已经修正了描述。
  • 能否制作一个源 XML 和目标 XML 示例?
  • 好的,我已经添加了一个例子。

标签: python xml


【解决方案1】:

可以使用lxml 提供remove_comments=False 选项来保留XML cmets:

from lxml import etree

parser = etree.XMLParser(remove_comments=False)
tree = etree.parse("input.xml", parser=parser)
root = tree.getroot()

for c in root.findall(".//string[@name='name']"):
    root.remove(c)

tree.write("output.xml")

“输入.xml”:

<root>
<!-- I am annotation -->
<string name="name">content</string><string left="left">left things</string>
</root>

“输出.xml”:

<root>
<!-- I am annotation -->
<string left="left">left things</string>
</root>

相关问题:

【讨论】:

    【解决方案2】:

    使用https://docs.python.org/2/library/xml.etree.elementtree.html

    import xml.etree.ElementTree as ET
    tree = ET.parse('data.xml')
    root = tree.getroot()
    
    for country in root.findall('//string[@name='left']'):
        root.remove(country)        
    
    tree.write('output_data.xml')
    

    【讨论】:

    • 我知道这样,那我会错过注释的。有没有其他办法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多