繁体   English   中英

为所有XML属性添加偏移量

[英]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("&", "&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更容易完成这些任务?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM