簡體   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