Parsing an XML file in python for emailing purposes

◇◆丶佛笑我妖孽 提交于 2021-02-11 10:25:47

问题


I am writing code in python that can not only read a xml but also send the results of that parsing as an email. Now I am having trouble just trying to read the file I have in xml. I made a simple python script that I thought would at least read the file which I can then try to email within python but I am getting a Syntax Error in line 4.

root.tag 'log'

Anyways here is the code I written so far:

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')]

Now the xml file has this type of formating

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

I want to be able to send an email of this xml file. For now though I am just trying to get the python code to read the xml file.


回答1:


response.find('log') won't find anything, because:

find(self, path, namespaces=None)

Finds the first matching subelement, by tag name or path.

In your case log is not a subelement, but rather the root element itself. You can get its text directly, though: response.text. But in your example the log element doesn't have any text in it, anyway.

EDIT: Sorry, that quote from the docs actually applies to lxml.etree documentation, rather than xml.etree.

I'm not sure about the reason, but all other calls to find also return None (you can find it out by printing response.find('date') and so on). With lxml ou can use xpath instead:

author = response.xpath('//author')[0].text
msg = [i.text for i in response.xpath('//msg')]

In any case, your use of find is not correct for msg, because find always returns a single element, not a list of them.



来源:https://stackoverflow.com/questions/12059648/parsing-an-xml-file-in-python-for-emailing-purposes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!