多个相同的标签名称和lxml.objectify

时间:2018-07-11 16:33:20

标签: python xml-parsing lxml.objectify

首先,感谢您对我的帖子的关注和帮助。

我一直注意到lxml.objetify的一个小问题。我正在将XLM作为字符串。 XLM的结构如下图所示:

<?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>

好吧,假设xml作为字符串存储在'r'变量中,当我使用以下函数时:

obj = lxml.objetify.fromstring(r)

obj对象的名称类似于:

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

可以看出,我错过了其他两项。您知道如何将所有xml作为对象吗?

非常感谢您,感谢我的英语错误

1 个答案:

答案 0 :(得分:1)

我刚刚找到了答案,为了帮助遇到同样问题的人,我将在此处发布答案。

要访问Item标记的每个子代,您可以像列表一样进行访问。我刚刚找到的最简单的方法是以下

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