没有得到xml文件输出

问题描述:

我想使用下面提供的python代码来读取xml文件email.xml(下面的数据),我不能够打印XML文件中存在的实际数据,但获得下面的输出。我哪里错了?没有得到xml文件输出

电流输出

xmlfile 
<open file 'email.xml', mode 'r' at 0x0226AF98> 
[<DOM Element: to at 0x231d620>] 
[<DOM Element: cc at 0x231d6c0>] 
[<DOM Element: bcc at 0x231d760>] 

Python代码

import xml.dom.minidom as minidom 

def getemaildata(): 
    # Open the XML file 
    xmlfile = open('email.xml','r') 
    print "xmlfile" 
    print xmlfile 
    dom = minidom.parse(xmlfile) 
    email=dom.getElementsByTagName('email') 
    for node in email: 
     toemail=dom.getElementsByTagName('to') 
     print toemail 
     ccemail=dom.getElementsByTagName('cc') 
     print ccemail 
     bccemail=dom.getElementsByTagName('bcc') 
     print bccemail 
return (toemail,ccemail,bccemail) 

def main(): 
(To,CC,BCC)=getemaildata() 

if __name__ == '__main__': 
main() 

email.xml文件

<email> 
    <to>[email protected];[email protected]; 
     [email protected];[email protected];</to> 
    <cc> data.team </cc> 
    <bcc>[email protected]</bcc>  
</email> 

您正在从XML解析器获取“元素”对象的列表。您需要进一步迭代才能找到实际的“文本”节点。

例如:

# this returns a list of all Elements that have the tag "to" 
toemail=dom.getElementsByTagName('to') 

# Here we take the first node returned with tag 'to', then it's first child node 
textnode = toemail[0].childNodes[0] 

# print the data in the textnode 
print textnode.data 

要清洁从文本节点中的地址:

for address in textnode.data.split(';'): 
    if address == '': 
     # Catch empty entries as a result of trailing ; 
     continue 
    email = i.strip().strip('\n') 
    print email 
+0

thanks..how格式化data..I看是越来越打印的数据原样不带任何格式像http://pastie.org/5398584 – user1795998

+0

我试图拆分和加入使用“;”但仍然相同tolist = textnode.data.split(';') print“;”。join(tolist) – user1795998

+0

XML将精确地存储两个标签之间的内容,因此您可以确保您的输入XML已被清理删除空白和换行符),或对每个地址执行清理。我在回答中添加了一个编辑,以显示如何完成这个感冒。理想情况下,您的电子邮件地址将分别存储在自己的标记中,而不是捆绑在一起,但我猜测您的输入XML数据来自电子邮件标题,因此您可能无法以更好的方式获取数据。 – Shootfast