试图理解元素树

Trying to understand the element tree

我正在尝试对 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'}>>>

因此我的子节点将是短信 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 的那些,即我在 return 中得到一个空白文件)。有趣的是,如果我将删除更改为地址 == 12345,我的输出文件将包括每个地址及其主体(因此它删除了日期、协议、类型和主题)。

I.E.

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

#output is:

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

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

编辑: 只想添加最后一件事,我认为这里的问题是它说没有地址=='that value' 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. 

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

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

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

所以 address 属性值是 string "51511",而不是 number 51511.

这解释了您的结果。