I've an XML-File
<?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>
, which contains different structures and attributes. Now I want to change the value of for example the attribute Pos by adding a certain offset, in this case 12. But I got an error.
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")
I get the following error
<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")
Does anyone see the error? Or are such tasks easier with XPath?
In ElementTree, attribute values must be strings explicitly, there is no automatic type conversion.
If you want to store something else, like an int
, you must do the conversion to string yourself. After all, when you read the attribute value, you got a string and did the conversion to int
yourself as well.
Using XPath will remove the need for nested loops.
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))
Also, unless there is a good reason, don't store XML files in legacy encondings like ISO-8859-1. Use Unicode encodings, like UTF-8.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.