查找 xml 标签,如果 python 2.7 和 ElementTree 不存在则跳过
Find xml tag and skip if it does not exists with python 2.7 and ElementTree
我有一个 XML 文件,如下所示。我想找到一个可能存在也可能不存在的特定标签。现在当我尝试
tree.find('./Altitude).text = '1000ft'
要更改高度值且我的标签不存在
我收到一个错误
'NoneType' object has no attribute 'text'
如果它不存在,但我想要的是让我的程序在它不存在时跳过该标记。
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
基本上我想做的是以下内容。
1.Search 特定标签的 xml 文件
2.If 有属性找到我们需要更改的属性并更改其值。
我停止使用 find() 方法。相反,我遍历整个树并检查我想要找到的标签,然后根据我创建的字典检查它。
for child in root.iter():
for key, val customDict.items():
if child.tag == key:
do something
这可能不是最好的方法,但它确实有效。
我有一个 XML 文件,如下所示。我想找到一个可能存在也可能不存在的特定标签。现在当我尝试
tree.find('./Altitude).text = '1000ft'
要更改高度值且我的标签不存在 我收到一个错误
'NoneType' object has no attribute 'text'
如果它不存在,但我想要的是让我的程序在它不存在时跳过该标记。
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
基本上我想做的是以下内容。 1.Search 特定标签的 xml 文件 2.If 有属性找到我们需要更改的属性并更改其值。
我停止使用 find() 方法。相反,我遍历整个树并检查我想要找到的标签,然后根据我创建的字典检查它。
for child in root.iter():
for key, val customDict.items():
if child.tag == key:
do something
这可能不是最好的方法,但它确实有效。