Skip to main content
 首页 » 编程设计

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

2024年12月31日8rubylouvre

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

请您参考如下方法:

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

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

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