处理xml文档中缺少的元素

2024-06-26 00:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些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,因此我想知道是否有更好的方法来解析这样的文档,其中有些元素是可选的。在


Tags: box元素原因passthemetryexceptcoordinates
2条回答

因为您只对findall的第一个元素感兴趣,所以可以用find(x)替换{}。此外,如果您想避免try/except块,可以使用三元。在

departedmembers = doc_root.findall('{http://www.ordnancesurvey.co.uk/xml/namespaces/osgb}departedMember')
for departedMember in departedMembers:
    ...
    date = departedmember[0].find('{http://www.ordnancesurvey.co.uk/xml/namespaces/osgb}deletionDate')
    date = None if date == None else date.text # Considering you want to set the element to None if it was not found

是的,问题不在于搜索方法,而是在没有返回元素时对返回元素的引用。您可以这样编写代码:

results = departedmember[0].findall('{http://www.ordnancesurvey.co.uk/xml/namespaces/osgb}deletionDate')

if results:
    date = results[0].text
else:
    # there is no element,
    # do what you want in this case

相关问题 更多 >