Файл my.py
import xml.etree.ElementTree as ET
import sys, errno
import os
resultFile = "result.txt"
xml = ET.parse('file1.xml')
root = xml.getroot()
try:
# clear result file
with open(resultFile, "w") as f:
f.write("----- begining file ----- \n")
# dictionary to check duplicate items
duplicatesDict = {}
for child in root:
# is duplicate item
workItemId = child.attrib['WorkItemId']
workItemRev = child.attrib['WorkItemRev']
uniq_key = workItemId + "-" + workItemRev
if uniq_key in duplicatesDict:
f.write("\n duplicate item with id=" + workItemId)
duplicatesDict[uniq_key] = ' '
# write text in file
f.write("--" + str(child.attrib))
if child.find("TTTSql") is not None:
f.write(child.find('TTTSql').text)
f.write("\n")
f.flush()
except Exception as e:
print(e)
sys.exit(errno.EACCES)
Файл my.sh
python my.py
# Below is the error catching mechanism
ret=$?
if [ $ret -ne 0 ]; then
echo "Error in XML to sql conversion"
$SHELL
exit 1
Файл file1.xml
<SchemaChanges>
<SchemaChange WorkItemId="1000" WorkItemRev="a" Description="Mike">
<TTTSql>
<![CDATA[
select * from book
]]>
</TTTSql>
</SchemaChange>
<SchemaChange WorkItemId="1001" WorkItemRev="a" Description="Rafaello">
<TTTSql>
<![CDATA[
select * from house
]]>
</TTTSql>
</SchemaChange>
</SchemaChanges>
создался файл result.txt
----- begining file -----
--{'WorkItemId': '1000', 'WorkItemRev': 'a', 'Description': 'Mike'}
select * from book
--{'WorkItemId': '1001', 'WorkItemRev': 'a', 'Description': 'Rafaello'}
select * from house