使用Objectify获取不同命名空间前缀的项目

0 投票
1 回答
1259 浏览
提问于 2025-04-16 12:00
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dd="http://example.com/ns/1.0" xml:lang="en-US">
<entry>
    <content type="html">Hello World!</content>
    <dd:country_code>USA</dd:country_code>
</entry>

我想用lxml.objectify来访问'Hello World!'和'USA'这两个内容。请问该怎么做呢?我不太在乎效率,只想要简单明了的方法。我试过我能想到的所有办法,但都没有成功。

1 个回答

1

使用这个设置:

import lxml.objectify as objectify
import io

content='''\
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dd="http://example.com/ns/1.0" xml:lang="en-US">
<entry>
    <content type="html">Hello World!</content>
    <dd:country_code>USA</dd:country_code>
</entry>
</feed>'''

doc=objectify.parse(io.BytesIO(content))
tree=doc.getroot()

简单快速的方法:

print(list(tree.entry.iterchildren()))
# ['Hello World!', 'USA']

或者更具体的方法:

print(tree.entry["content"])
# Hello World!

来处理命名空间:

print(tree.entry["{http://example.com/ns/1.0}country_code"])
# USA

这种访问命名空间的方法在这里有详细说明

撰写回答