使用lxml模块获取XML属性值 [英] Getting XML attribute value with lxml module

查看:969
本文介绍了使用lxml模块获取XML属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用lxml模块获取XML文件的属性值?

How can i get the value of an attribute of XML file with lxml module?

我的XML看起来像这样"

My XML looks like this"

<process>
   <name>somename</name>
   <statistics>
     <stats param='someparam'>
        <value>0.456</value>
        <real_value>0.4</value>
     </stats>
     <stats ...>
      .
      .
      .
     </stats>
   </statistics>
</process>

我想从value属性获取值0.456.我正在遍历属性并获取文本,但是我不确定这是执行此操作的最佳方法

I want to get the value 0.456 from the value attribute. I'm iterating trought the attribute and getting the text but im not sure that this is the best way for doing this

for attribute in root.iter('statistics'):
   for stats in attribute:
      for param_value in stats.iter('value'):
          value = param_value.text

还有其他更简单的方法吗?类似于stats.get_value('value')

is there any other much easier way for doing this? something like stats.get_value('value')

推荐答案

使用 XPath :

root.find('.//value').text

这将为您获取第一个value标记的内容.

This gets you the content of the first value tag.

如果要遍历所有value元素,请使用findall,这将为您提供所有元素的列表.

If you want to iterate over all value elements, use findall, this gets you a list with all the elements.

如果只希望在<stats param='someparam'>元素内包含value元素,则使路径更具体:

If you only want the value elements inside <stats param='someparam'> elements, make the path more specific:

root.findall("./statistics/stats[@param='someparam']/value")


请注意,find/findall 仅支持XPath的子集.如果要利用整个XPath(1.x)功能,请使用xpath方法.


edit: Note that find/findall only support a subset of XPath. If you want to make use of the whole XPath (1.x) functionality, use the xpath method.

这篇关于使用lxml模块获取XML属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆