2011-02-17 28 views
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來訪問'Hello World!'和'美國'。如何做呢?我不關心效率,只是簡單。我嘗試了所有我能想到的無用功。使用objectify獲取具有不同名稱空間前綴的項目

回答

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 

這種訪問命名空間的方法是documented here

相關問題