繁体   English   中英

试图理解元素树

[英]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'}>>>

因此,我的子节点将是 sms IE:

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

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

IE

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

#output is:

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

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

编辑:只是想添加最后一件事,我相信这里的问题是它说没有地址=='那个值' 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 的 output 只给我地址和正文。理论上,因为没有什么等于那个值,它应该给我与我的输入完全相同的 output (包括日期、类型和主题)。

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

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

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

这解释了你的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM