繁体   English   中英

Python:如何使用lxml解析带句点的xml标签?

[英]Python: How do you use lxml to parse xml tags with periods?

我正在尝试使用适用于Python的lxml模块来解析Jenkin的job XML文件。 看起来像这样:

<triggers>
    <hudson.triggers.TimerTrigger>
       <spec>H H(6-21)/3 * * *</spec>
</hudson.triggers.TimerTrigger>

我喜欢使用lxml的方便的objectify模块,但在尝试执行此操作时会感到困惑:

root.triggers.hudson.triggers.TimerTrigger.spec = 'something'

我得到AttributeError: no such child: hudson 当然,没有名为hudson的属性! 这样如何处理一块愚蠢的XML?

对于其他上下文,这是我的代码:

from lxml import objectify
import jenkins

j = jenkins.Jenkins('http://local.jenkins.instance')
xml = j.get_job_config('job_name')
root = objectify.fromstring(xml)
root.triggers.hudson.triggers.TimerTrigger.spec = 'something'

以下使用lxmletree模块的代码对我etree ,它从<spec>获取文本:

from lxml import etree

root = etree.parse("37757193.xml").getroot()
spec = root.xpath("//triggers/hudson.triggers.TimerTrigger/spec")[0]
print(spec.text)

返回'HH(6-21)/3 * * *'

确实有必要将triggers.hudson.triggers.TimerTrigger解释为尝试访问以下结构中的<TimerTrigger>元素,因此它抱怨在给定OP的实际XML时找不到hudson子元素:

<triggers> 
  <hudson> 
    <triggers> 
      <TimerTrigger> 
        <spec>H H(6-21)/3 * * *</spec> 
      </TimerTrigger> 
    </triggers> 
  </hudson> 
</triggers>

访问名称包含点而无需切换到etree子元素的一种可能方法是使用__getattr__()方法:

>>> root.triggers.__getattr__('hudson.triggers.TimerTrigger').spec
'H H(6-21)/3 * * *'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM