使用文本文件为etree xml提供输入



我有一个xml文件,需要从etee更改该xml文件中的2个参数。

XML file:
<?xml version="1.0"?>
<ABC_Input xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<REQ>  
<!-- Optional in XSD -->
<INFO>ALL</INFO>
</REQ>
<PO>
<PO_ID>3557698</PO_ID>
<!-- Req in XSD -->
<RAN>HQF011512C</RAN>
<!-- Req in XSD -->
</PO>
</ABC_Input>

我已经写了下面的代码来实现这个

import xml.etree.ElementTree as ET
tree = ET.parse('alpha.xml')
root = tree.getroot()
for val in root.findall('PO')
   val.find('RAN').text="HQ123"
tree.write('output1.xml')

现在我需要传递RAN&来自文本文件的PO_ID作为输入,那么这怎么可能呢?

试试这个:

import xml.etree.ElementTree as ET
# Read the file (called alpha.txt) and extract the lines
lines = []
with open('alpha.txt', 'r') as txtF:
    lines = txtF.readlines()
# A dictionary to hold PO_ID and RAN values 
values = {}
# If there are multiple values of PO_ID or RAN then it will take the last entry in the text file
for line in lines:
    line = line.strip()
    if 'RAN' in line:
        values['RAN'] = line[line.find('RAN')+len('RAN')+1:]
    elif 'PO_ID' in line:
        values['PO_ID'] = line[line.find('PO_ID')+len('PO_ID')+1:]
    else:
        continue
tree = ET.parse('alpha.xml')
root = tree.getroot()
for val in root.findall('PO'):
    val.find('PO_ID').text = values['RAN']
    val.find('RAN').text = values['PO_ID']
tree.write('output1.xml')

最新更新