Python 在解析之前如何检查 XML 中的属性和标签是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15568126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check the existence of attributes and tags in XML before parsing?
提问by Abhishek
I'm parsing an XML file via Element Tree in python and and writing the content to a cpp file.
我正在通过 python 中的元素树解析 XML 文件,并将内容写入 cpp 文件。
The content of children tags will be variant for different tags. For example first event tag has party tag as child but second event tag doesn't have.
不同标签的子标签内容会有所不同。例如,第一个事件标签将派对标签作为子标签,但第二个事件标签没有。
-->How can I check whether a tag exists or not before parsing?
-->如何在解析前检查标签是否存在?
-->Children has value attribute in 1st event tag but not in second. How can I check whether an attribute exists or not before taking it's value.
-->Children 在第一个事件标签中有 value 属性,但在第二个没有。如何在获取属性值之前检查属性是否存在。
--> Currently my code throws an error for non existing party tag and sets a "None" attribute value for the second children tag.
--> 目前,我的代码为不存在的派对标签引发错误,并为第二个子标签设置了“无”属性值。
<main>
<event>
<party>Big</party>
<children type="me" value="3"/>
</event>
<event>
<children type="me"/>
</event>
</main>
Code:
代码:
import xml.etree.ElementTree as ET
tree = ET.parse('party.xml')
root = tree.getroot()
for event in root.findall('event'):
parties = event.find('party').text
children = event.get('value')
I want to check the tags and then take their values.
我想检查标签,然后获取它们的值。
采纳答案by Martijn Pieters
If a tag doesn't exist, .find()indeed returns None. Simply test for that value:
如果标签不存在,则.find()确实返回None. 只需测试该值:
for event in root.findall('event'):
party = event.find('party')
if party is None:
continue
parties = party.text
children = event.get('value')
You already use .get()on event to test for the valuethe attribute; it returns Noneas well if the attribute does not exist.
您已经使用.get()on 事件来测试value属性;None如果属性不存在,它也会返回。
Attributes are stored in the .attribdictionary, so you can use standard Python techniques to test for the attribute explicitly too:
属性存储在.attrib字典中,因此您也可以使用标准 Python 技术显式测试属性:
if 'value' in event.attrib:
# value attribute is present.

