【问题标题】:Trying to understand the element tree试图理解元素树
【发布时间】:2019-11-10 22:06:35
【问题描述】:

我正在尝试对一个 xml 文件(我的短信)进行一些简单的修改,但我很难理解到底发生了什么以及为什么。

我的 xml 文件实际上是这样格式化的:

<sms count="123456" backupset="123456" backupdate="12345"....>
     <sms protocol="0" address="51511" date="1531363846440" type="1" subject="null" body="Welcome to Family Mobile! Your number is: ....>
     <sms protocol="0" address="58038" date="1531407417581" type="1" subject="null" body="Family Mobile Important Message:...>
...

因此当我创建一棵树时:

import xml.etree.ElementTree as ET
import os

os.chdir('C:/Users/Sams PC/Desktop/')

tree = ET.parse("text_messages.xml")
root = tree.getroot()

我的根标签和属性是:

>>>root.tag
'smses'
>>> root.attrib
{'count': '6079', 'backup_set': '1233456', 'backup_date': '12345'}>>>

因此,我的子节点将是 sms I.E.:

for child in root:
...     print(child.tag, child.attrib)
...
sms {'protocol': '0', 'address': '51511', 'date': '1531363846440', 'type': '1', 'subject': 'null', 'body': 'Welcome to Family Mobile! Your number is: ...}
sms {'protocol': '0', 'address': '58038', 'date': '1531407417581', 'type': '1', 'subject': 'null', 'body': 'Family Mobile Important Message: ...}

因此,如上所述,我想做的是从特定数字中选择文本。所以这是我的方法。

for sms in root.findall('sms'):
    address=sms.get('address')
    if address != 51511:
        root.remove(sms)


tree.write('output.xml')

所以这个想法基本上是,在 sms 行中搜索并获取地址中的每个值,然后通过说如果值不等于 12345 来过滤这些地址,然后删除整个 sms 行(换句话说,只保留文本编号 12345)。

但是,相反,我的输出文件删除了每一行短信(即使是地址值为 12345 的短信,即我得到一个空白文件作为回报)。有趣的是,如果我将删除更改为地址 == 12345,那么我的输出文件将包含每个地址及其正文(因此它删除了日期、协议、类型和主题)。

I.E.

if address == 51511:
        root.remove(sms)

#output is:

<sms address="51511" body="Welcome to Family Mobile! Your number is:..>

在这一点上,我不知道为什么我得到了我得到的输出,并且觉得我一定误解了这个元素树是如何工作的。任何帮助将不胜感激!谢谢!

编辑: 只是想添加最后一件事,我相信这里的问题是它说没有地址=='那个值' IE。如果我这样做:

for sms in root.findall('sms'):
    address=sms.get('address')
    body=sms.get('body')
    if address==51511:
        print(address,body)

#output is nothing. However if I do address!=51511, I get every address with its associated body as an output. Basically implying that value of address does not exist in my xml file. 

所以前面的命令实际上是有效的,我得到一个空白文件,因为我的地址值都不等于值 51511(我仍然不知道为什么 ==51511 的输出只给了我地址和正文. 从理论上讲,由于没有什么等于那个值,它应该给我与我的输入完全相同的输出(包括日期、类型和主题)。

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

    您可能会在问题中注意到,当您打印 child.attrib 时,您会得到:

    {..., 'address': '51511', ...}
    

    所以address 属性值是字符串 "51511",而不是数字 51511

    这解释了你的结果。

    【讨论】:

    • 哇,这就是问题所在。谢谢!
    • 最后一件事,为什么协议、日期、类型和主题在写入新文件时都会被删除?我的新文件只显示我指定的值的地址,但现在输出是这样的:```
      在同样的方面,虽然这是无意的,但我该如何让它只覆盖特定的部分(即我可以写 print(address,body),这只会给我地址及其关联的正文,我该如何制作,所以我只能将地址和正文写入新文件。顺便说一下,对不起所有的 cmets,它告诉我 5 分钟后我不允许编辑 cmets。跨度>
    • 没关系,找到了。似乎 pop 命令正是我想要的。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签