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

时间:2014-09-24 09:13:12

标签: python-2.7 elementtree

我有一个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&amp;的价值从文本文件中输入PO_ID作为输入,那怎么可能?

1 个答案:

答案 0 :(得分:0)

试试这个:

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