[英]Use Python to remove unneeded elements from XML file
我正在 Python 中编写一个程序来使用 API,它似乎不会根据用户是否被视为活跃来过滤掉请求。 当我向 API 询问活跃用户列表时,我得到了一个更长的 XML 文档,看起来像下面的文本,它仍然包括<active>
标签为 false 的用户。
<ArrayOfuser xmlns="WebsiteWhereDataComesFrom.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<user>
<active>false</active>
<datelastlogin>2/3/2014 10:21:13 PM</datelastlogin>
<dept>0</dept>
<email/>
<firstname>userfirstname</firstname>
<lastname>userlastname</lastname>
<lastupdated/>
<lastupdatedby/>
<loginemail>userloginemail</loginemail>
<phone1/>
<phone2/>
<rep>userinitials</rep>
</user>
<user>
<active>true</active>
<datelastlogin>8/21/2019 9:16:30 PM</datelastlogin>
<dept>3</dept>
<email>useremail</email>
<firstname>userfirstname</firstname>
<lastname>userlastname</lastname>
<lastupdated>2/6/2019 11:10:29 PM</lastupdated>
<lastupdatedby>userinitials</lastupdatedby>
<loginemail>userloginemail</loginemail>
<phone1>userphone</phone1>
<phone2/>
<rep>userinitials</rep>
</user>
</ArrayOfuser>
该程序需要最终仅从活动用户返回<rep>
标记的列表。
这是我作为这个项目的开始尝试的代码。 我可能过于复杂了,因为我试图为活跃用户解析 users.xml 然后保存一个包含所有关于活跃用户的 XML 数据的文件,然后在该文件中使用 for 循环从每个<rep>
标签获取信息并保存它到一个列表:
to_remove = ['<active>false</active>']
with open('users.xml') as xmlfile, open('activeusers.xml','w') as newfile:
for line in xmlfile:
if not any(remo in line for remo in to_remove):
newfile.write(line)
在 activeusers.xml 中,我期待看到下面的代码块。
<ArrayOfuser xmlns="WebsiteWhereDataComesFrom.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<user>
<active>true</active>
<datelastlogin>8/21/2019 9:16:30 PM</datelastlogin>
<dept>3</dept>
<email>useremail</email>
<firstname>userfirstname</firstname>
<lastname>userlastname</lastname>
<lastupdated>2/6/2019 11:10:29 PM</lastupdated>
<lastupdatedby>userinitials</lastupdatedby>
<loginemail>userloginemail</loginemail>
<phone1>userphone</phone1>
<phone2/>
<rep>userinitials</rep>
</user>
</ArrayOfuser>
结果是用户 xml 文件的相同副本。 我的猜测是,如果程序正在复制所有内容,它必须正确读取文件,但它绝对不会删除我需要的内容,因此语法一定不正确。 这只是我想到的解决方案,程序不必创建一个名为 activeusers.xml 的新文件。 最终目标是只为活跃用户获取<rep>
标签列表,所以如果有更好的方法,我很想知道,因为我是 XML 的新手和 Python 的新手。
由于您正在处理 xml,因此您应该使用适当的 xml 解析器。 请注意,在这种情况下,您还必须处理名称空间。
所以试试这个:
from lxml import etree
#load your file
doc = etree.parse("users.xml")
#declare namespaces
ns = {'xx': 'WebsiteWhereDataComesFrom.com'}
#locate your deletion targets
targets = doc.xpath('//xx:user[xx:active="false"]',namespaces=ns)
for target in targets:
target.getparent().remove(target)
#save your file
with open("newfile.xml", 'a') as file:
file.write(etree.tostring(doc).decode())
这应该有您预期的 output。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.