[英]Add offset to all XML attributes
我有一個XML文件
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<PageDescription>
<Page>
<Row />
<Row>
<Cell cellRow="0" cellColumn="0" Pos="693" />
<Cell cellRow="0" cellColumn="1" Pos="2693" />
</Row>
</Page>
</PageDescription>
,其中包含不同的結構和屬性。 現在,我想通過添加一定的偏移量(例如12)來更改屬性Pos的值,但出現錯誤。
for currfile in allfiles:
filepathstr = xmldir + "/" + currfile;
tree = xee.ElementTree(file=filepathstr)
for tag in tree.findall('Page'):
for tag2 in tag.findall('Row'):
for tag3 in tag2.findall('Cell'):
selectTag = tag3.attrib['Pos']
newVal = int(selectTag)+12
tag3.set('Pos', newVal)
expfilename = expdir + "/" + currfile
tree.write(expfilename,encoding="ISO-8859-1")
我收到以下錯誤
<class 'xml.etree.ElementTree.ElementTree'>
---------------------------------------------------------------------------
TypeError
Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\xml\etree\ElementTree.py in _escape_attrib(text)
1079 try:
-> 1080 if "&" in text:
1081 text = text.replace("&", "&")
TypeError: argument of type 'int' is not iterable
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-2-b1ffea99d1f3> in <module>()
67 expfilename = expdir + "/" + currfile
68
---> 69 tree.write(expfilename,encoding="ISO-8859-1")
有人看到錯誤了嗎? 還是使用XPath更容易完成這些任務?
在ElementTree中,屬性值必須是明確的字符串,沒有自動類型轉換。
如果要存儲其他內容(例如int
,則必須進行轉換以自己進行字符串化。 畢竟,當您讀取屬性值時,您得到了一個字符串,並且也將自己轉換為int
。
使用XPath將消除對嵌套循環的需要。
for currfile in allfiles:
tree = xee.ElementTree(os.path.join(xmldir, currfile))
for cell in tree.findall('./Page/Row/Cell'):
pos = int(cell.get('Pos'))
cell.set('Pos', str(pos + 12))
tree.write(os.path.join(expdir, currfile))
另外,除非有充分的理由,否則不要以ISO-8859-1之類的舊式格式存儲XML文件。 使用Unicode編碼,例如UTF-8。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.