如何在解析之前检查XML中属性和标记的存在?

时间:2021-07-21 07:18:48

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.

子标记的内容对于不同的标记是不同的。例如,第一个事件标记作为子事件标记有party tag,而第二个事件标记没有。

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

——>子节点在第一个事件标签中有value属性,在第二个事件标签中没有。如何在获取属性值之前检查属性是否存在。

--> Currently my code throws an error for non existing party tag and sets a "None" attribute value for the second children tag.

——>目前,我的代码对不存在的party标记抛出错误,并为第二个子标记设置“None”属性值。

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

我要检查标签,然后取它们的值。

1 个解决方案

#1


42  

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 value the attribute; it returns None as well if the attribute does not exist.

您已经使用.get()来测试该属性的值;如果属性不存在,则返回None。

Attributes are stored in the .attrib dictionary, 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.

#1


42  

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 value the attribute; it returns None as well if the attribute does not exist.

您已经使用.get()来测试该属性的值;如果属性不存在,则返回None。

Attributes are stored in the .attrib dictionary, 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.