根据特殊标志从XML文件中删除行

时间:2018-11-27 10:13:07

标签: python xml filter

我的文件包含不同的标签。

根据标签,我想根据标签中的值删除行。

例如cellColumn> 20,xPos> 2000或xpos> 200 && xPos>4000。

是否有建议的方法?还是包裹?

<OwnCell cellRow="20" cellColumn="103" xPos="24901" widthPx="49" value="22" />
<OwnCell cellRow="20" cellColumn="104" xPos="25137" widthPx="49" value="25" />
<OwnCell cellRow="21" cellColumn="105" xPos="25373" widthPx="49" value="31" />
<OwnCell cellRow="20" cellColumn="106" xPos="25609" widthPx="49" value="28" />
<OwnCell cellRow="24" cellColumn="107" xPos="25845" widthPx="49" value="19" />
<OwnCell cellRow="20" cellColumn="108" xPos="26081" widthPx="49" value="19" />

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以按以下方式过滤文档

import xml.etree.ElementTree as xee
data='''\
<root>
  <OwnCell cellRow="20" cellColumn="103" xPos="24901" widthPx="49" value="22" />
<OwnCell cellRow="20" cellColumn="104" xPos="25137" widthPx="49" value="25" />
<OwnCell cellRow="21" cellColumn="105" xPos="25373" widthPx="49" value="31" />
<OwnCell cellRow="20" cellColumn="106" xPos="25609" widthPx="49" value="28" />
<OwnCell cellRow="24" cellColumn="107" xPos="25845" widthPx="49" value="19" />
<OwnCell cellRow="20" cellColumn="108" xPos="26081" widthPx="49" value="19" />
</root>
'''
doc=xee.fromstring(data)

for tag in doc.findall('OwnCell'):
    if int(tag.attrib['cellRow'])<=20: #add your filter condition here
        doc.remove(tag)
print(xee.tostring(doc))

首先找到要过滤的所有元素 然后添加您的条件以排除与此条件匹配的元素