在解析之前,如何检查XML中属性和标记的存在? [英] How can I check the existence of attributes and tags in XML before parsing?

查看:82
本文介绍了在解析之前,如何检查XML中属性和标记的存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过python中的Element Tree解析XML文件,并将内容写入cpp文件.

I'm parsing an XML file via Element Tree in python and and writing the content to a cpp file.

子标签的内容将因不同标签而异.例如,第一个事件标签将party标签作为子标签,而第二个事件标签则没有.

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.

->目前,我的代码为不存在的party标签引发了错误,并为第二个child标签设置了"None"属性值.

--> 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>

代码:

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.

推荐答案

如果标签不存在,则.find()确实返回None.只需测试该值即可:

If a tag doesn't exist, .find() indeed returns None. Simply test for that value:

for event in root.findall('event'):
    party = event.find('party')
    if party is None:
        continue
    parties = party.text
    children = event.get('value')

您已经在事件中使用.get()来测试value属性;如果该属性不存在,它也会返回None.

You already use .get() on event to test for the value the attribute; it returns None as well if the attribute does not exist.

属性存储在.attrib词典中,因此您也可以使用标准的Python技术来显式测试该属性:

Attributes are stored in the .attrib dictionary, so you can use standard Python techniques to test for the attribute explicitly too:

if 'value' in event.attrib:
    # value attribute is present.

这篇关于在解析之前,如何检查XML中属性和标记的存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆