Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python lxml loop through all tags

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.

like image 383
roymustang86 Avatar asked May 07 '26 11:05

roymustang86


1 Answers

You could try it with the 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
like image 144
Birei Avatar answered May 10 '26 04:05

Birei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!