我廣泛關注過去幾天,似乎無法找到我要找的。我已經使用Python 2.7.3和ElementTree編寫了一個腳本來解析XML文件並編輯深埋在XML文件中的屬性。該腳本正常工作。上週晚些時候,我與客戶通了一個會議,他告訴我目標平臺是CentOS。我想,沒問題。爲了測試我創建了一個CentOS的VMware客戶端和出乎我的意料我的腳本crapped牀上預期的平臺,讓我有錯誤訊息,「語法錯誤:預期路徑分隔符([])」在我研究的性質的過程這個錯誤信息讓我瞭解到CentOS 6.4支持Python 2.6.6,它包含了一個老版本的ElementTree,它不支持搜索屬性[@attribute]語法。
這個客戶不會在平臺上升級的Python,也不會安裝額外的庫,所以LXML不是我的選擇。我的問題是,我能以某種方式訪問隱藏的屬性並在沒有ElementTree對[@attribute]工具的支持的情況下進行編輯嗎?ElementTree的語法錯誤:預期路徑分隔符([])
這裏是我處理的一種XML的一個例子:
`
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<my-gui>
<vehicles>
<car vendor="Ford"/>
</vehicles>
<options>
<line transmission='manual'/>
</options>
<title>Dealership</title>
<choice id='manual' title="Dealership">
<pkg-deal id='manual' auth='manager'>.</pkg-deal>
</choice>
<choice id='manual' title='Dealership'/>
<choice id='manual' DealerLocation='Dealer_Loc'/>
<choices-outline color='color_choice'>
<line choice='blue'/>
</choices-outline>
<choice id='cars' GroupID='convertables'>
<pkg-deal id='model.Taurus' version="SEL" arguments='LeatherInterior' enabled='XMRadio'>Taurus</pkg-deal>
<pkg-deal id='model.Mustang' version="GT" enabled='SIRIUSRadio'>Mustang</pkg-deal>
<pkg-deal id='model.Focus' version="SE" enabled='XMRadio'>Focus</pkg-deal>
<pkg-deal id='model.Fairlane'>Fairlane</pkg-deal>
<pkg-deal id='model.Fusion' version="SE" arguments='ClothInerior'>Fusion</pkg-deal>
<pkg-deal id='model.Fiesta' version="S Hatch" enabled="SIRIUSRadio">Fiesta</pkg-deal>
</choice>
</my-gui>
`
下面是Python的2.6.6下打破了成功的Python 2.7.3代碼片段:
if self.root.iterfind('pkg-deal'):
self.deal = self.root.find('.//pkg-deal[@id="model.fusion"]')
self.arg = str(self.deal.get('arguments'))
if self.arg.find('with Scotchguard=') > 0:
QtGui.QMessageBox.information(self, 'DealerAssist', 'The selected car is already updated. Nothing to do.')
self.leave()
self.deal.set('arguments', self.arg + ' with Scotchguard')
...
...
有沒有一種方法,我可以修改這個「如果」語句塊,讓我編輯的融合元素的「參數」屬性的第一線?還是我退居實施libxml2的,這將是一個真正的痛苦?...
感謝。
我不知道這是否包括安裝額外的庫(這是一種側面問題),但也許你可以嘗試複製和粘貼的版本[ElementTree的在Python 2.7(http://hg.python.org/cpython/file/2.7/Lib/xml/etree/ElementTree.py)到腳本,並將該文件重命名爲'ElementTree2.py'並使用它? – Michael0x2a
@ Michael0x2a - 哇!我沒有想到這一點。這非常有創意,可能只是工作。我想我可以將它作爲一個單獨的文件並將其導入。我會玩這個,讓你知道。 –
@ Michael0x2a - 我試着複製ElementTree.py,將它重命名爲ElementTree2.py並導入它,但一直得到無效的導入錯誤。雖然好想。 –