如何在解析之前检查 XML 中是否存在属性和标签?

2023-08-29Python开发问题
19

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

问题描述

我正在通过 Python 中的元素树解析 XML 文件,并将内容写入 cpp 文件.

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

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

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 在第一个事件标签中具有 value 属性,但在第二个事件标签中没有.如何在取值之前检查属性是否存在.

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

--> 目前我的代码对不存在的派对标签抛出错误,并为第二个子标签设置无"属性值.

--> 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 中是否存在属性和标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11