且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用lxml模块获取XML属性值

更新时间:2023-11-25 08:07:52

使用 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.