2017-03-06 60 views
0

我只是想分析一个XML文件,该文件是一样的解析Python中的XML文件,该文件嵌套的标签是有

<?xml version="1.0" encoding="UTF-8"?><Significant Major="3" Minor="0" Revision="1" xmlns="urn:reuterscompanycontent:significantdevelopments03"><RepNo>0091N</RepNo><CompanyName Type="Primary">XYZ</CompanyName><Production Date="2017-02-23T18:10:39" /><Developments><Development ID="3534388"><Dates><Source>2017-02-23T18:18:32</Source><Initiation>2017-02-23T18:18:32</Initiation><LastUpdate>2017-02-23T18:23:26</LastUpdate></Dates><Flags><FrontPage>0</FrontPage><Significance>1</Significance></Flags><Topics><Topic1 Code="254">Regulatory/Company Investigation</Topic1></Topics><Headline>FTC approves final order settling charges for Abbott's deal with St. Jude Medical</Headline></Development></Developments></Significant> 

我只是想分析的发展标记和解析它的每一个嵌套的标签 我有下面的代码:

import xml.etree.cElementTree as ET 
tree = ET.ElementTree(file='../rawdata/SigDev_0091N.xml') 

#get the root element 
root = tree.getroot() 

#print root.tag, root.attrib 

for child in root: 
#print child.tag, child.attrib 
    name = child.tag 
    print name 
    print 'at line 13' 
    if name is 'Developments': 
     print 'at line 15' 
     for devChild in name['Developments']: 
      print devChild.tag,devChild.attrib 

它不会去if区块内,我不知道为什么?

+1

你缩进这里搞砸!它是否也在脚本文件中? – jkalden

+0

否否不在脚本文件中缩进非常正确 – ggupta

+0

在文章左下角有一个编辑按钮。请使用它来更正您的格式。 Python *关心*关于格式化.... –

回答

3

检查name is 'Developments'总是返回false作为child.tag返回{xmlns}tagname格式的值。

对于您的情况:

名= {瓮:reuterscompanycontent:significantdevelopments03}发展

您可参照本question的答案。

简单字符串方法strip(),find(),split()re可以帮助您跳过名称空间进行比较。

Python文档相关:https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml-with-namespaces

+0

你可以帮我解析它吗?假设我想要在开发中获得源的价值,那么我将如何? – ggupta

+0

它帮助我解决了我的问题,谢谢:) – ggupta

0

对不起@Gaurav,我不明白这一点, 打印(名称)给出:

{urn:reuterscompanycontent:significantdevelopments03}Developments 

,并要检查,如果它是“发展”。 您可以确认我执行代码时是否做错了。 我不能把评论(声誉)。

+0

我在我的xmlns XML,所以它正在追加到每个输出。你可以忽略这一点,并请提供给我正确的方法来解析开发标记 – ggupta

+0

好吧,name!= Developements,因此它不会在if里面。我想我们必须解析字符串。 so ... names.split('}')[1] ==开发。 我还会错吗? –