Last active
August 29, 2015 14:01
-
-
Save hedgeven/5acb416bc7705ac3588b to your computer and use it in GitHub Desktop.
simple xmlparser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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