0
<?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を使用して、両方の「HelloWorld!」にアクセスしたいと思います。および「USA」。どのようにそれを行うことができますか?私は効率には関心がなく、ただの節約に関心があります。私は考えられるすべてのことを無駄に試しました。

4

1 に答える 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

名前空間にアクセスするこの方法は、ここに記載されています

于 2011-02-17T17:24:26.200 に答える