我有一个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>
,包含不同的结构和属性 . 现在我想通过添加一个特定的偏移来改变例如属性Pos的值,在这种情况下为12.但是我得到了一个错误 .
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更容易完成此类任务?
1 回答
在ElementTree中,属性值必须是显式字符串,没有自动类型转换 .
如果你想存储其他东西,比如
int
,你必须自己进行转换 . 毕竟,当你读取属性值时,你得到了一个字符串并自己转换为int
.使用XPath将消除对嵌套循环的需求 .
此外,除非有充分的理由,否则不要将XML文件存储在ISO-8859-1等传统的enconding中 . 使用Unicode编码,如UTF-8 .