python - 处理 xml 文档中缺失的元素

标签 python xml xml.etree

我有一些 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>

我正在解析它:

departedmembers = doc_root.findall('{http://www.ordnancesurvey.co.uk/xml/namespaces/osgb}departedMember')
for departedMember in departedMembers:
    findWhat='{http://www.ordnancesurvey.co.uk/xml/namespaces/osgb}DepartedFeature'
    fid = int(departedmember.find(findWhat).attrib['fid'].replace('osgb', ''))
    theme=departedmember[0].findall('{http://www.ordnancesurvey.co.uk/xml/namespaces/osgb}theme')[0].text    
    reason=departedmember[0].findall('{http://www.ordnancesurvey.co.uk/xml/namespaces/osgb}reasonForDeparture')[0].text
    date=departedmember[0].findall('{http://www.ordnancesurvey.co.uk/xml/namespaces/osgb}deletionDate')[0].text

有时原因或日期或两者都是空的,即元素丢失,而不仅仅是内容为空。根据 XSD,这是合法的,但我在尝试选择不存在的元素的文本时遇到属性错误。为了解决这个问题,我将原因和日期行放在 try 中,除了 block ,例如:

try:
    date=departedmember[0].findall('{http://www.ordnancesurvey.co.uk/xml/namespaces/osgb}deletionDate')[0].text
except:
    pass

这行得通,但我讨厌像这样使用 except/pass,所以这让我想知道是否有更好的方法来解析这样的文档,其中某些元素是可选的。

最佳答案

由于您只对 findall 的第一个元素感兴趣,因此可以将 findall(x)[0] 替换为 find(x)。此外,如果你想避免 try/except block ,你可以使用三元。

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

关于python - 处理 xml 文档中缺失的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22716169/

相关文章:

python - nmap-python 无法在 Raspberry Pi 上正确安装

php - 收到的 HTTP 方法无效。只接受 POST

python-3.x - 更好的 Python 3 XML 序列化程序

xpath - '._ElementUnicodeResult' 的问题

python - 使用 etree Python 解析 xml

python - Starlette JSONResponse 到 Pydantic parse_obj_as

python - 为什么 PyAutoGui LocateOnScreen() 只返回 None

python - 解析带有前缀标签的 .xml? xml.etree.元素树

python - openpyxl - comment.author 在 xlsx 文件中不可见

java - android:translationY 属性隐藏 Edittext 的下边框