python lxml loop through all tags

假装没事ソ 提交于 2020-12-13 09:34:59

问题


I have a dict mapping each xml tag to a dict key. I want to loop through each tag and text field in the xml, and compare it with the associated dict key value which is the key in another dict.

<2gMessage>
    <Request>
        <pid>daemon</pid>
        <emf>123456</emf>
        <SENum>2041788209</SENum>
        <MM>
            <MID>jbr1</MID>
            <URL>http://jimsjumbojoint.com</URL>
        </MM>
        <AppID>reddit</AppID>
        <CCS>
            <Mode>
                <SomeDate>true</CardPresent>
                <Recurring>false</Recurring>
            </Mode>
            <Date>
                <ASCII>B4788250000028291^RRR^15121015432112345601</ASCII>
            </Date>
            <Amount>100.00</Amount>
        </CCS>
    </Request>
</2gMessage>

The code I have so far:

parser = etree.XMLParser(ns_clean=True, remove_blank_text=True)
tree   = etree.fromstring(strRequest, parser)
for tag in tree.xpath('//Request'):
    subfields = tag.getchildren()
    for subfield in subfields:
        print (subfield.tag, subfield.text)
return strRequest

But, this only prints the tags which are direct children of Request, I want to be able to access the subchildren on children if it is an instance in the same loop. I don't want to hardcode values, as the tags and structure could be changed.


回答1:


You could try with iter() function. It will traverse through all the children elements. The comparison of the length is to print only those that has no children:

A complete script like this one:

from lxml import etree
tree = etree.parse('xmlfile')
for tag in tree.iter():
    if not len(tag):
        print (tag.tag, tag.text)

Yields:

pid daemon
emf 123456
SENum 2041788209
MID jbr1
URL http://jimsjumbojoint.com
AppID reddit
CardPresent true
Recurring false
ASCII B4788250000028291^RRR^15121015432112345601
Amount 100.00


来源:https://stackoverflow.com/questions/28415352/python-lxml-loop-through-all-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!