باستخدام تعريف للحصول على العناصر باستخدام بادئة مساحة اسم مختلفة
سؤال
giveacodicetagpre.
أود استخدام lxml.Objectify للوصول إلى كل من "Hello World!"و "الولايات المتحدة الأمريكية".كيف يمكن أن تتم؟أنا لست مهتما بالكفاءة، فقط parsimony.لقد جربت كل ما يمكنني التفكير فيه دون جدوى.
المحلول
With this setup:
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()
The short and quick way:
print(list(tree.entry.iterchildren()))
# ['Hello World!', 'USA']
Or the more specific way:
print(tree.entry["content"])
# Hello World!
to handle namespaces:
print(tree.entry["{http://example.com/ns/1.0}country_code"])
# USA
This method of accessing namespaces is documented here.
لا تنتمي إلى StackOverflow