简体   繁体   English

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

[英]Mutiple same tag names and lxml.objectify

I have been noticing a little issue with lxml.objetify.我一直注意到 lxml.objetify 的一个小问题。 I am getting XLM as a string.我将 XLM 作为字符串获取。 The XLM presents an structure like shown down below: 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>

Well, assuming the xml as a string is stored in 'r' variable, When I use the following function:好吧,假设 xml 作为字符串存储在 'r' 变量中,当我使用以下函数时:

obj = lxml.objetify.fromstring(r)

The obj objects appear like: obj 对象看起来像:

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?您知道如何将所有 XML 作为对象获取吗?

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.要访问 Item 标签的每个子项,您可以像列表一样访问。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM