Reputation: 331
I am trying to iterate through one XML file in Python with ElementTree, change one attribute in a tag and then insert that tag into another tag in another file, code below:
import xml.etree.ElementTree as ET
tree = ET.parse('original_file.xml')
root = tree.getroot()
cnt = 1
exact = ET.Element("eExact")
glentries = ET.SubElement(exact, "GLEntries")
glentry = ET.SubElement(glentries, "GLEntry", status="E", entry="194100751")
ET.SubElement(glentry, "DocumentDate").text = "31032019"
ET.SubElement(glentry, "Description").text = "TEST"
ET.SubElement(glentry, "Journal", code="41", type="M")
for child in root.iter('FinEntryLine'):
child.attrib["number"] = cnt
ET.SubElement(glentry, child)
cnt += 1
tree = ET.ElementTree(exact)
tree.write("output_file.xml")
However this does not work, because ElemntTree and SubElement are reporting that they can't serialiaze. Is there another way in doing it, but so I do not have to iterate though all the subtags of "child"?
Input file:
<eExact>
<GLEntries>
<GLEntry status="E" entry="194100751">
<DocumentDate>31032019</DocumentDate>
<Description>TEST</Description>
<Journal code="41" type="M"></Journal>
<FinEntryLine number="83932" type="N" subtype="N">
<Description>01032019 GWPC 1900005105</Description>
</FinEntryLine>
<FinEntryLine number="98457" type="N" subtype="N">
<Description>01032019 GWPC 1900005105</Description>
</FinEntryLine>
</GLEntry>
</GLEntries>
</eExact>
Output should just change number tag into sequence, starting from 1.
Upvotes: 0
Views: 202
Reputation: 51052
If you just want to change the number
attribute of the <FinEntryLine>
elements, this is all that is needed:
import xml.etree.ElementTree as ET
tree = ET.parse('original_file.xml')
cnt = 1
for child in tree.iter('FinEntryLine'):
child.attrib["number"] = str(cnt)
cnt += 1
tree.write("output_file.xml")
Result (output_file.xml):
<eExact>
<GLEntries>
<GLEntry entry="194100751" status="E">
<DocumentDate>31032019</DocumentDate>
<Description>TEST</Description>
<Journal code="41" type="M" />
<FinEntryLine number="1" subtype="N" type="N">
<Description>01032019 GWPC 1900005105</Description>
</FinEntryLine>
<FinEntryLine number="2" subtype="N" type="N">
<Description>01032019 GWPC 1900005105</Description>
</FinEntryLine>
</GLEntry>
</GLEntries>
</eExact>
Upvotes: 1