向所有XML属性添加偏移量

2024-04-26 03:51:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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。但我错了。你知道吗

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("&", "&amp;")

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更容易完成这些任务?你知道吗


Tags: textinpostreeforpagecelliso
1条回答
网友
1楼 · 发布于 2024-04-26 03:51:57

在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))

另外,除非有充分的理由,否则不要将XML文件存储在ISO-8859-1这样的旧式编码中。使用Unicode编码,如UTF-8。你知道吗

相关问题 更多 >