我試圖使用Python中LXML模塊來解析詹的工作的XML文件。它看起來像這樣:Python:你如何使用lxml解析帶句點的xml標籤?
<triggers>
<hudson.triggers.TimerTrigger>
<spec>H H(6-21)/3 * * *</spec>
</hudson.triggers.TimerTrigger>
我喜歡使用LXML的得心應手客觀化模塊
,但是當我試圖做到這一點會很困惑:
root.triggers.hudson.triggers.TimerTrigger.spec = 'something'
我得到一個AttributeError: no such child: 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'
只是一個猜測,但你可能需要使用'etree'代替。 – MattDMo
這太糟糕了,因爲我真的很喜歡清潔客觀化的東西。我注意到我可以做'root.triggers.getchildren()[0] .spec = period',但這看起來像一個黑客。 –
如果有效,請使用它。我發現使用XPath與客觀化一樣簡單明瞭,它可以處理包含句點和冒號的複雜標記,但對每個標記都有效。 – MattDMo