[英]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'
確實有必要將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.