在 XML 文件中查找文本并转换为大写

Find Text In XML File and Convert To Uppercase

我收到了 XML 个文件,我需要将字段名称更改为全部大写字母。我正在尝试在 Python 中自动执行此操作,但只能将文件的整行转换为全部大写。

有没有办法只大写之间的文本:

<Index Name="NAME">Name to Capitalize</Index> 

在 Python 中看起来像这样?:

<Index Name="NAME">NAME TO CAPITALIZE</Index>

我被告知要尝试 python 将其自动化。目前我们使用批处理脚本或手动更改文本。这是我目前所拥有的。

import re

file_input  = 'index.XML'
file_output = 'output.XML'

with open(file_input) as file_object:
    for line in file_object:   

        # replace the effected line with all caps
        if re.search('<Index Name="NAME">', line): 
            line = line.upper().rstrip()
        line = line.rstrip()
        print(line)

        # write each line to a file
        file_output = open("output.XML", 'a')
        file_output.write(line + '\n')

对于有问题的代码,可以按如下方式更改以获得所需的结果。 或者也可以用xmltree-

import re
f=open(r'input.xml', "r")
f_out = open("output.XML", 'a')

newtag=''

while(True):
    line = f.readline()
    if  not line:
        break
    if re.search('<Index Name="NAME">', line): 
        newtag = line [:line.find('>')+1] + line[line.find('>')+1:line.find('</')].upper() + line[line.find('</'):]
        print (newtag, end="") ## Not needed for this code
    else:
        newtag = line
    f_out.write(newtag)

将产生结果为 -

$ more input.xml
<Index Name="NAME">name to capitalize</Index>
<Index Name="NAME">name to capitalize</Index>
<Index Name="IDX1">name to capitalize</Index>
<Index Name="NAME">name to capitalize</Index>
<Index Name="IDX2">name to capitalize</Index>

$ python replace_in_file.py
<Index Name="NAME">NAME TO CAPITALIZE</Index>
<Index Name="NAME">NAME TO CAPITALIZE</Index>
<Index Name="NAME">NAME TO CAPITALIZE</Index>

$ more output.XML
<Index Name="NAME">NAME TO CAPITALIZE</Index>
<Index Name="NAME">NAME TO CAPITALIZE</Index>
<Index Name="IDX1">name to capitalize</Index>
<Index Name="NAME">NAME TO CAPITALIZE</Index>
<Index Name="IDX2">name to capitalize</Index>