2

我注意到 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 作为对象吗?

4

1 回答 1

1

我刚刚找到答案,为了帮助有同样问题的人,我将在这里发布答案。

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

for item in obj.Items:
    # Do something with item object/element
    print('Id: '  + str(item.id) + ' Properties: ' + item.properties)
于 2018-07-11T16:43:59.823 回答