Skip to content

Instantly share code, notes, and snippets.

@hedgeven
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hedgeven/5acb416bc7705ac3588b to your computer and use it in GitHub Desktop.
Save hedgeven/5acb416bc7705ac3588b to your computer and use it in GitHub Desktop.
simple xmlparser
#!/usr/bin/env python3
from urllib.request import urlopen
import xml.etree.ElementTree as ET
import os
import sys
import re
def help():
print("Usage: "+ __file__+ " TARGET..."+
"\nSimple script for parsing local and remote xml files")
def parse(xml_file,remote):
if remote:
try:
tree = ET.parse(urlopen(xml_file))
except:
return print("Can't parse "+xml_file)
else:
tree = ET.parse(xml_file)
root = tree.getroot()
for country in root.iter('country'):
print(country.attrib['name'])
for neighbor in country.iter('neighbor'):
print("\t"+neighbor.attrib['name'])
def main(argv):
if len(argv)>0:
for arg in argv:
if re.match(r'^-', arg):
return help()
for arg in argv:
if re.match(r'^http', arg):
print("Parsing file "+arg+":")
parse(arg,True)
print("-------------------")
elif os.path.isfile(arg):
print("Parsing file "+arg+":")
parse(arg,False)
print("-------------------")
else:
print("File "+arg+" is not found\n-------------------")
else:
help()
sys.exit(1)
if __name__ == "__main__":
main(sys.argv[1:])
""" example for input xml file
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment