我正在用 python 编写代码,它不仅可以读取 xml,还可以将解析结果作为电子邮件发送。现在我在尝试读取 xml 中的文件时遇到了麻烦。我制作了一个简单的 python 脚本,我认为它至少会读取该文件,然后我可以尝试在 python 中通过电子邮件发送该文件,但我在第 4 行中收到语法错误。
root.tag '日志'
无论如何,这是我到目前为止编写的代码:
import xml.etree.cElementTree as etree
tree = etree.parse('C:/opidea.xml')
response = tree.getroot()
log = response.find('log').text
logentry = response.find('logentry').text
author = response.find('author').text
date = response.find('date').text
msg = [i.text for i in response.find('msg')]
现在 xml 文件具有这种类型的格式
<log>
<logentry
revision="12345">
<author>glv</author>
<date>2012-08-09T13:16:24.488462Z</date>
<paths>
<path
action="M"
kind="file">/trunk/build.xml</path>
</paths>
<msg>BUG_NUMBER:N/A
FEATURE_AFFECTED:N/A
OVERVIEW:Example</msg>
</logentry>
</log>
我希望能够发送此 xml 文件的电子邮件。目前,我只是想获取 python 代码来读取 xml 文件。
最佳答案
response.find('log')
找不到任何东西,因为:
find(self, path, namespaces=None)
Finds the first matching subelement, by tag name or path.
在您的情况下 log
不是子元素,而是根元素本身。不过,您可以直接获取其文本:response.text
。但在您的示例中,log
元素中无论如何都没有任何文本。
编辑:抱歉,文档中的引用实际上适用于 lxml.etree
文档,而不是 xml.etree
。
我不确定原因,但对 find
的所有其他调用也返回 None
(您可以通过打印 response.find( '日期')
等等)。与lxml
您可以使用 xpath
代替:
author = response.xpath('//author')[0].text
msg = [i.text for i in response.xpath('//msg')]
无论如何,您对 find
的使用对于 msg
来说都是不正确的,因为 find
始终返回单个元素,而不是列表他们。
关于python - 在 python 中解析 XML 文件以用于发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12059648/