fork download
  1. #!/usr/bin/python
  2. # Alternative Implementation with ElementTree XML Parser
  3.  
  4. xml = '''\
  5. <Emps>
  6. <Emp>
  7. <Name>Raja</Name>
  8. <Location>
  9. <city>ABC</city>
  10. <geocode>123</geocode>
  11. <state>XYZ</state>
  12. </Location>
  13. <sal>100</sal>
  14. <type>temp</type>
  15. </Emp>
  16. <Emp>
  17. <Name>GsusRecovery</Name>
  18. <Location>
  19. <city>Torino</city>
  20. <geocode>456</geocode>
  21. <state>UVW</state>
  22. </Location>
  23. <sal>120</sal>
  24. <type>perm</type>
  25. </Emp>
  26. </Emps>
  27. '''
  28.  
  29. from xml.etree import ElementTree as ET
  30. # tree = ET.parse('input.xml') # decomment to parse xml from file
  31. tree = ET.ElementTree(ET.fromstring(xml))
  32. root = tree.getroot()
  33.  
  34. for location in root.iter('Location'):
  35. if location.find('city').text == 'Torino':
  36. location.set("isupdated", "1")
  37. location.find('city').text = 'MyCity'
  38. location.find('geocode').text = '10.12'
  39. location.find('state').text = 'MyState'
  40.  
  41. print ET.tostring(root, encoding='utf8', method='xml')
  42. # tree.write('output.xml') # decomment if you want to write to file
Success #stdin #stdout 0.03s 9360KB
stdin
Standard input is empty
stdout
<?xml version='1.0' encoding='utf8'?>
<Emps>
    <Emp>
        <Name>Raja</Name>
        <Location>
            <city>ABC</city>
            <geocode>123</geocode>
            <state>XYZ</state>
        </Location>
        <sal>100</sal>
        <type>temp</type>
    </Emp>
    <Emp>
        <Name>GsusRecovery</Name>
        <Location isupdated="1">
            <city>MyCity</city>
            <geocode>10.12</geocode>
            <state>MyState</state>
        </Location>
        <sal>120</sal>
        <type>perm</type>
    </Emp>
</Emps>