使用python进行xml过滤

use*_*215 5 python xml xpath elementtree

我有一个以下的xml文档:

<node0>
    <node1>
      <node2 a1="x1"> ... </node2>
      <node2 a1="x2"> ... </node2>
      <node2 a1="x1"> ... </node2>
    </node1>
</node0>
Run Code Online (Sandbox Code Playgroud)

我想过滤掉node2什么时候a1="x2".用户提供需要测试和过滤掉的xpath和属性值.我在像BeautifulSoup这样的python中查看了一些解决方案,但它们太复杂了,不保留文本的大小写.我想保持文档与以前一样过滤掉一些东西.

你能推荐一个简单而简洁的解决方案吗?从它的外观来看,这不应该太复杂.实际的xml文档并不像上面那么简单,但想法是一样的.

unu*_*tbu 6

这使用xml.etree.ElementTree标准库中的内容:

import xml.etree.ElementTree as xee
data='''\
<node1>
  <node2 a1="x1"> ... </node2>
  <node2 a1="x2"> ... </node2>
  <node2 a1="x1"> ... </node2>
</node1>
'''
doc=xee.fromstring(data)

for tag in doc.findall('node2'):
    if tag.attrib['a1']=='x2':
        doc.remove(tag)
print(xee.tostring(doc))
# <node1>
#   <node2 a1="x1"> ... </node2>
#   <node2 a1="x1"> ... </node2>
# </node1>
Run Code Online (Sandbox Code Playgroud)

这使用lxml,它不在标准库中,但具有更强大的语法:

import lxml.etree
data='''\
<node1>
  <node2 a1="x1"> ... </node2>
  <node2 a1="x2"> ... </node2>
  <node2 a1="x1"> ... </node2>
</node1>
'''
doc = lxml.etree.XML(data)
e=doc.find('node2/[@a1="x2"]')
doc.remove(e)
print(lxml.etree.tostring(doc))

# <node1>
#   <node2 a1="x1"> ... </node2>
#   <node2 a1="x1"> ... </node2>
# </node1>
Run Code Online (Sandbox Code Playgroud)

编辑:如果node2更深入地隐藏在xml中,那么您可以遍历所有标记,检查每个父标记以查看该node2元素是否是其子项之一,如果是,则将其删除:

仅使用xml.etree.ElementTree:

doc=xee.fromstring(data)
for parent in doc.getiterator():
    for child in parent.findall('node2'):
        if child.attrib['a1']=='x2':
            parent.remove(child)
Run Code Online (Sandbox Code Playgroud)

使用lxml:

doc = lxml.etree.XML(data)
for parent in doc.iter('*'):
    child=parent.find('node2/[@a1="x2"]')
    if child is not None:
        parent.remove(child)
Run Code Online (Sandbox Code Playgroud)

  • @OrclUser:有关 XML 的快速概述,其中将解释元素和属性之间的区别,请参阅 [DiveIntoPython 第 12 章](http://www.diveintopython3.net/xml.html)。有关 Python 标准库 xml.etree 的教程,请参阅 [Doug Hellman 的本周模块](http://pymotw.com/2/xml/etree/ElementTree/parse.html)。有关 `lxml.etree` 的更多信息,请参阅 [lxml.etree 教程](http://lxml.de/tutorial.html)。要快速介绍 XPath,您可以从 [此处](http://www.w3schools.com/xpath/default.asp) 和 [此处供参考](http://www.w3.org/TR/ xpath/)。 (2认同)