【问题标题】:Python parsing XML using ElementTree based on IF ConditionsPython使用基于IF条件的ElementTree解析XML
【发布时间】:2018-06-08 02:13:05
【问题描述】:

使用 Python,我正在尝试解析 XML 文件以检索基于“名称”属性值的元素值和基于“名称”属性值的子元素值好吧。

条件是:

如果'test'元素中的Category属性为3,则获取'name'属性的值

如果“name”属性的值为“enable”,则获取“color”元素的值

示例代码:

<test category="1">
 <test category="2">
  <test name="1" category="3">
   <color name="disable">blue</color>
   <color name="disable">yellow</color>
   <color name="enable">red</color>
   <color name="disable">orange</color>
  </test>
  <test name="2" category="3">
   <color name="disable">green</color>
   <color name="disable">purple</color>
   <color name="enable">white</color>
   <color name="disable">gray</color>
  </test>
 </test>
</test>

预期结果:

1 个红色

2 白色

我当前的代码:

import xml.etree.ElementTree as ET
tree = ET.parse('C:/colors.xml')
root = tree.getroot()

for test in root.getiterator('test'):

if test.attrib['category']=="3":
    print test.attrib['name']

这给了我:

1
2

我尝试了一个嵌套的 FOR 来获取颜色元素的值,但我尝试的一切似乎都是从头开始的。

我们将不胜感激!

谢谢

【问题讨论】:

  • 出了点问题。该 xml 不会使用 ElementTree 为我解析。
  • 根据xmlvalidation.com也坏了。
  • 是的对不起,我试图从记忆中做一个样本。我更新了它,它现在应该可以验证...谢谢让我知道!

标签: python xml scripting elementtree


【解决方案1】:
  • 请记住,您的 XML 格式不正确(属性值应该用引号括起来)
  • color 标签不匹配

您的逻辑使用了代码中缺少的 2 个条件。

string = '''<test category="1">
<test category="2">
<test name="1" category="3">
<color name="disable">blue</color>
<color name="disable">yellow</color>
<color name="enable">red</color>
<color name="disable">orange</color>
</test>
<test name="2" category="3">
<color name="disable">green</color>
<color name="disable">purple</color>
<color name="enable">white</color>
<color name="disable">gray</color>
</test>
</test>
</test>'''

from xml.etree import ElementTree as ET

root = ET.fromstring(string)

for test_node in root.iter('test'):
    if test_node.attrib['category'] == "3":
        for color_element in test_node.iter('color'):
            if color_element.attrib['name'] == 'enable':
                print(test_node.attrib['name'], color_element.text)

#  1 red
#  2 white

【讨论】:

  • 啊..完美!谢谢
猜你喜欢
  • 2021-02-06
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 2017-03-16
相关资源
最近更新 更多