【问题标题】:How do i extract XML tags/entity with the same name?如何提取具有相同名称的 XML 标记/实体?
【发布时间】:2021-12-02 11:52:54
【问题描述】:

你可以从我的 xml 中看到,它有两个菠萝,我想提取它的值。我对python很陌生,希望你能帮助我!

-<csData>
-<entity name="1" parentEntity="123" type='a'>

<attribute name="ab" value = ""/>

**<attribute name="pineapple" value = "0.9099"/>**

<attribute name="ac" value = ""/>

-<entity name="0" parentEntity="234" type='a'>

<attribute name="ab" value = ""/>

**<attribute name="pineapple" value = "0.2881"/>**

<attribute name="ac" value = ""/>
</csData>

所以我想在这里提取 PINEAPPLE 的值,这里是我拥有的代码:

def extract_pineapple(self, cd, cs, pineapple, root):
  data = {'cd_id': cd_id, 'cs_id'=cs=id}
  for c in root.findall("./csData/entity[@type='a']"):
     for attr in c.findall("./attribute[@name:'pineapple']:
         data['pineapple'] = c.find("./attribute[@name='pineapple'].get('value')
return [data]

输出: 它只提取了一个值: 菠萝:0.2881 菠萝:0.2881

我想要的是: 菠萝:0.2881 菠萝:0.9099

【问题讨论】:

    标签: python xml parsing tags


    【解决方案1】:

    以下似乎有效

    import xml.etree.ElementTree as ET
    
    xml = '''<csData>
    <entity name="1" parentEntity="123" type="a"/>
    
    <attribute name="ab" value = ""/>
    
    <attribute name="pineapple" value = "0.9099"/>
    
    <attribute name="ac" value = "" />
    
    <entity name="0" parentEntity="234" type="a"/>
    
    <attribute name="ab" value = ""/>
    
    <attribute name="pineapple" value = "0.2881"/>
    
    <attribute name="ac" value = ""/>
    </csData>'''
    
    root = ET.fromstring(xml)
    values = [e.attrib['value'] for e in root.findall('.//attribute[@name="pineapple"]')]
    print(values)
    

    输出

    ['0.9099', '0.2881']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2014-01-19
      相关资源
      最近更新 更多