python - 根据特殊标志从 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" />
谢谢!
解决方案
您可以按以下方式过滤您的文档
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))
首先找到要过滤的所有元素,然后添加条件以排除符合此条件的元素
推荐阅读
- python - 同时枚举两个列表
- php - 如何在多个文件中使用 PHP Autoloader?
- android - 无法执行 apkanalyzer
- kubernetes - 设备上没有剩余空间,这是意料之外的。Kubernetes 集群中卷的 MountVolume.SetUp 失败
- .net - MediatR 处理程序注册在集成测试请求上失败
- vue.js - 安装和使用 node-Sqlite3 后 Electron 显示空白屏幕
- javascript - 带有 Typescript 的 ReactJS 不接受具有属性的对象
- php - 如何从 url 获取变量以在查询中工作?PHP
- c# - 使用 System.IO 在 c# 中将文件转换为数组
- typo3 - 点击 Typo3 9 中的 Lightbox 而不是放大?