Parse xml with lxml - extract element value

前端 未结 3 605
有刺的猬
有刺的猬 2020-12-17 19:25

Let\'s suppose we have the XML file with the structure as follows.

 


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 20:24

    I would be more direct in your XPath: go straight for the elements you want, in this case datafield.

    >>> for df in doc.xpath('//datafield'):
            # Iterate over attributes of datafield
            for attrib_name in df.attrib:
                    print '@' + attrib_name + '=' + df.attrib[attrib_name]
    
            # subfield is a child of datafield, and iterate
            subfields = df.getchildren()
            for subfield in subfields:
                    print 'subfield=' + subfield.text
    

    Also, lxml appears to let you ignore the namespace, maybe because your example only uses one namespace?

提交回复
热议问题