python. 如何通过libxml2获取属性值
我之前在用MINIDOM,但它没有提供xpath的方法。
现在我在尝试使用libxml2,但在获取属性值时遇到了麻烦。
我的xml大概长这样:
<Class name="myclass1" version="0">
<Owner user-login="smagnoni"/>
</Class>
我写了以下代码:
import libxml2
doc = libxml2.parseFile(file)
ris = doc.xpathEval('*/Class[@name="'+className+'" and @version="'+classVersion+'"]/Owner')
print str(ris[0])
结果是:
<Owner user-login="smagnoni"/>
我怎么才能只得到“smagnoni”?手动解析这个字符串感觉太麻烦了。不过我没有找到类似于.getAttribute("属性名")
在minidom中的方法。
有没有人能建议我正确的方法,或者给我指个文档?
3 个回答
2
lxml 是一个库,它使用了 libxml2,并提供了一个更友好的接口(也就是ElementTree API),这样你就能享受到 libxml2 的快速处理速度和它的 xpath 查询功能。
import lxml.etree as ET
doc = ET.parse(file)
owner = doc.find('/*/Class[@name="'+className+'" and @version="'+classVersion+'"]/Owner')
if owner:
print owner.get('user-login')
另外一个好处是,Element Tree API 在 Python 2.5 中默认就可以使用(不过在 1.5 版本中没有包含 [@name='value']
这种 xpath 语法,这个是在 Python 2.7 中添加的,但你可以在旧的 2.x 版本中单独获取1.3 API)。
你可以通过以下方式导入任何兼容的 ElementTree API 版本:
try:
from lxml import etree
print("running with lxml.etree")
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
print("running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
print("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
print("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
print("running with ElementTree")
except ImportError:
print("Failed to import ElementTree from any known place")
5
.prop('user-login')
应该可以正常使用:
import libxml2
import io
content='''\
<Class name="myclass1" version="0">
<Owner user-login="smagnoni"/>
</Class>
'''
doc = libxml2.parseMemory(content,len(content))
className='myclass1'
classVersion='0'
ris = doc.xpathEval('//Class[@name="'+className+'" and @version="'+classVersion+'"]/Owner')
elt=ris[0]
print(elt.prop('user-login'))
会得到
smagnoni
4
for owner in ris:
for property in owner.properties:
if property.type == 'attribute':
print property.name
print property.content
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。