我只想解析一个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>
我只想解析Development标记并解析其每个嵌套标记 我有以下代码:
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块,我不知道为什么?
答案 0 :(得分:3)
检查false
始终返回child.tag
,{xmlns}tagname
将返回strip()
格式的值。
对于你的情况:
name = {urn:reuterscompanycontent:significantdevelopments03}发展
您可以参考此question的答案。
简单字符串方法find()
,split()
,re
或{{1}}可以帮助您跳过命名空间进行比较。
相关的Python文档:https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml-with-namespaces