【问题标题】:Iter through XML tags and get tag inside that attribute - Python遍历 XML 标记并获取该属性内的标记 - Python
【发布时间】:2018-11-19 22:39:51
【问题描述】:

我正在寻找 xml 数据中的子标签值,我下面的代码获取了 xml 数据中“信息”中标签“颜色”的所有值,但我正在寻找迭代,

如果颜色 = 黄色,我只需要获得它的排名。

****我的代码:****

xmldata = '''
 <FullGroup>
    <color>General</color>
    <link>url</link>
    <three>test</three>
    <four>
      <info>
        <color>yellow</color>
        <rank>100</rank>
        <place>first</place>
      </info>
      <info>
        <color>red</color>
        <rank>500</rank>
        <place>second</place>
      </info>
     </four>
 </FullGroup>'''  

xml = ElementTree.fromstring(xmldata)
for color in xml.findall('.//info/color'):
   print color.text

output: 
yellow
red

Required output:
100

在此先感谢..

【问题讨论】:

    标签: python xml


    【解决方案1】:

    你可以像这样使用zip()

    for color, rank in zip(xml.findall('.//info/color'), xml.findall('.//info/rank')):
        if color.text == 'yellow':
            print(rank.text)
    

    【讨论】:

    • AttributeError: 'str' object has no attribute 'findall'.... 错误,是否将 xml 数据作为字符串读取?
    【解决方案2】:

    您的 XPath 表达式错误。要获取所有 info 元素的 rank 子元素,这些元素的子元素名为 colortext() 值为“yellow”,请更改

    xml = ElementTree.fromstring(xmldata)
    for color in xml.findall('.//info/color'):
       print color.text
    

    xml = ElementTree.fromstring(xmldata)
    for curRank in xml.findall('.//info[color="yellow"]/rank'):
       print curRank.text
    

    输出为:

    100
    

    【讨论】:

    • 谢谢!!完成
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多