Search code examples
pythonxml-parsinglxml.objectify

Mutiple same tag names and lxml.objectify


I have been noticing a little issue with lxml.objetify. I am getting XLM as a string. The XLM presents an structure like shown down below:

<?xml version="1.0" ?>
<ItemResponse>
    <Items>
        <Item>
            <id>1</id>
            <properties>Item 1 properties cames here</properties>
        </Item>
        <Item>
            <id>2</id>
            <properties>Item 2 properties cames here</properties>
        </Item>

        <Item>
            <id>3</id>
            <properties>Item 3 properties cames here</properties>
        </Item>
    </Items>
</ItemResponse>

Well, assuming the xml as a string is stored in 'r' variable, When I use the following function:

obj = lxml.objetify.fromstring(r)

The obj objects appear like:

obj
|--Items
     |--Item
          |--id = 1
          |--properties = 'Item 1 properties cames here'

As can be seen, I am missing the other two items. Do you know how to get all the XML as object?


Solution

  • I just found the answer, In order to help people with the same issue, I will post the answer here.

    To access to every children of Item tag, you can access like a list. The easiest way I just found is the following

    for item in obj.Items:
        # Do something with item object/element
        print('Id: '  + str(item.id) + ' Properties: ' + item.properties)