解析svn list命令的输出 - 无法获取属性

时间:2013-06-11 08:27:05

标签: python xml-parsing lxml

我正在使用保存的输出:

svn list -R --xml directory

作为python脚本的输入,我使用python 2.6.5的当前代码:

import os
import os.path
import sys
import lxml.etree

if len(sys.argv) == 2:
    in_filename = str(sys.argv[1])
    if os.path.isfile (in_filename):
        for ent in lxml.etree.parse (in_filename).iter ('entry'):
            get = ent.xpath
            if ent.get ("kind") == "file":
                log_filename = get ('string(name)')
                log_revision = get ('string(revision)') # This needs Fixing!
                log_date = get ('string(commit/date)')
                print('{0},{1},{2}'.format(log_revision,log_date[:10],log_filename))

我无法从条目中提取revision="1581"属性(只需1581是我需要的),其条目如下所示:

<entry kind="file">
  <name>path/file.c</name>
  <size>3973</size>
  <commit revision="1581">
    <author>user</author>
    <date>2012-09-06T15:40:13.396582Z</date>
  </commit>
</entry>

我可以轻松地获得其他所有内容,只是没有看到如何获得不在条目顶层的属性。

谢谢(如果这是一个noob问题,请道歉)。

2 个答案:

答案 0 :(得分:1)

Revision是commit元素的一个属性,因此正确的xpath语法是commit/@revision,所以:

import os
import os.path
import sys
import lxml.etree

if len(sys.argv) == 2:
    in_filename = str(sys.argv[1])
    if os.path.isfile (in_filename):
        for ent in lxml.etree.parse (in_filename).iter ('entry'):
            get = ent.xpath
            if ent.get ("kind") == "file":
                log_filename = get ('string(name)')
                log_revision = get('string(commit/@revision)') # Fixed ;)
                log_date = get ('string(commit/date)')
                print('{0},{1},{2}'.format(log_revision,log_date[:10],log_filename))

答案 1 :(得分:1)

这也有效:

log_revision = ent.find('commit').get("revision")