首页 > 解决方案 > 根据特殊标志从 XML 文件中删除行

问题描述

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

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

例如 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" />

谢谢!

标签: pythonxmlfilter

解决方案


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

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))

首先找到要过滤的所有元素,然后添加条件以排除符合此条件的元素


推荐阅读