如何处理没有值的XML属性?

2024-10-02 08:21:22 发布

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

我目前正在编写一个程序,解析许多XML文件。 我感兴趣的一个属性如下所示: XML Attribute

我想提取这个标签的值。有时,某些XML文件包含此标记,但没有值,这会破坏我的代码:

citation = document.getElementsByTagName("r3d:citationGuidelineURL")

for cit in citation:
        print(cit.firstChild.nodeValue)

如何检查是否存在节点值并停止程序因属性错误而崩溃


Tags: 文件代码标记程序属性attribute标签xml
1条回答
网友
1楼 · 发布于 2024-10-02 08:21:22

基于元素树的解决方案

import xml.etree.ElementTree as ET

xml = '''<root>
   <a>value1</a>
   <a></a> 
   <a>value2</a>     
</root>'''

doc = ET.fromstring(xml)
a_list = doc.findall("a")
for a in a_list:
    if a.text:
        print(a.text)
    else:
        print('Empty Element')

输出

value1
Empty Element
value2

相关问题 更多 >

    热门问题