Sreejith Menon
Sreejith Menon

Reputation: 1087

Parsing XML using python using xmldom or etree

I have an XML in the below format:

<root>
    <child>
        <param1> 1 </param1>
        <param2> 2 </param2>
    </child>

    <other_child>
        <grand_child>
            <param>a</param>
            <param>b</param>
        </grand_child>
        <grand_child2>
            <param>c</param>
            <param>d</param>
        </grand_child2>
    </other_child>
</root>

I have been using the below code snippets to parse it.

root = eTree.parse(configFile).getroot()

for child in root:
    for g_child in child:
        print(g_child.tag, g_child.attrib)

This is the output I get:

param1 {}
param2 {}
grand_child {}
grand_child2 {}

I also tried minidom and it gives me similar results.

Thanks in advance.

Upvotes: 0

Views: 30

Answers (1)

somesingsomsing
somesingsomsing

Reputation: 3350

If you want to print the values of the params you can do something like:

for child in root:
    for g_child in child:
        print(g_child.text)
        for g in g_child:
            print(g.text)

This was my output (Notice the spaces)

1 
2 


a
b


c
d

Upvotes: 1

Related Questions