我有一些XML,其中的一个片段如下:
<osgb:departedMember>
<osgb:DepartedFeature fid='osgb4000000024942964'>
<osgb:boundedBy>
<gml:Box srsName='osgb:BNG'>
<gml:coordinates>188992.575,55981.029 188992.575,55981.029</gml:coordinates>
</gml:Box>
</osgb:boundedBy>
<osgb:theme>Road Network</osgb:theme>
<osgb:reasonForDeparture>Deleted</osgb:reasonForDeparture>
<osgb:deletionDate>2014-02-19</osgb:deletionDate>
</osgb:DepartedFeature>
</osgb:departedMember>
我正在分析它:
^{pr2}$有时原因或日期或两者都是空的,即元素丢失,而不仅仅是空内容。根据XSD,这是合法的,但是我在尝试选择不存在的元素的文本时遇到属性错误。为了解决这个问题,我把原因和日期行放在try中,除了块,比如:
try:
date=departedmember[0].findall('{http://www.ordnancesurvey.co.uk/xml/namespaces/osgb}deletionDate')[0].text
except:
pass
这是可行的,但我不喜欢像这样使用except/pass,因此我想知道是否有更好的方法来解析这样的文档,其中有些元素是可选的。在
因为您只对}。此外,如果您想避免try/except块,可以使用三元。在
findall
的第一个元素感兴趣,所以可以用find(x)
替换{是的,问题不在于搜索方法,而是在没有返回元素时对返回元素的引用。您可以这样编写代码:
相关问题 更多 >
编程相关推荐