Getting XML attribute value with lxml module

冷暖自知 提交于 2019-12-07 20:28:36

问题


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

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>

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

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


回答1:


Use XPath:

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

This gets you the content of the first value tag.

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

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

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

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.



来源:https://stackoverflow.com/questions/24241700/getting-xml-attribute-value-with-lxml-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!