I'm currently using xml.etree.cElementTree in Python to parse XML files. I would like to know if it's possible to read data from another file and insert it at a specific location in an XML file.
Here's the XML file I'm working with:
<Data>
<Action>A</Action>
<FinalDate>2018-08-24</FinalDate>
<InitialDate>2011-08-19</InitialDate>
<DateOperation>
<DateOperationCode>Append</DateOperationCode>
<Date>2017-08-21</Date>
</DateOperation>
<Data>
In this file, I would like to insert dates that are read from another file as text after the line "2017-08-21", so that the updated XML file can look like this:
<Data>
<Action>A</Action>
<FinalDate>2018-08-24</FinalDate>
<InitialDate>2011-08-19</InitialDate>
<DateOperation>
<DateOperationCode>Append</DateOperationCode>
<Date>2017-08-21</Date>
<Date>2017-09-21</Date> #new date
<Date>2017-10-21</Date> #new date
<Date>2017-11-21</Date> #new date
</DateOperation>
<Data>
I tried different ways to insert the dates, but none have worked so far.
I would recommend, in this case, using lxml instead of ElementTree, because of the former's better xpath support.
Also, both your xml files are not well formed, for various reasons.
So, assuming I understand you correctly, I would do the following:
Output:
I notice that file1, after the modifications, looks very much like file2. If that's the case in real life, why not just use file2?