by
4,346 39
8
1,744 Views
7 Badges
Top 1% !
Popular
Famous
Nice
Tagged
Specified
OpenSource
Popularity: 42nd place
Created
Modified Jun 30, 2013

Published on:

LanguagePython
LanguageXML
Architecturex86_64

python xml parse

Here how to parse a xml file in python.
post this code
<iframe id="embedFrame" style="width:600px; height:300px;" src="http://www.snip2code.com/Embed/991/python-xml-parse"></iframe>
Click on the embed code to copy it into your clipboard Width:Height:
Leave empty to retrieve all the content First Line:Last Line:
try:
    import cElementTree as ET
except ImportError:
  try:
    # Python 2.5 need to import a different module
    import xml.etree.cElementTree as ET
  except ImportError:
    exit_err("Failed to import cElementTree from any known place")      

def find_in_tree(tree, node):
    found = tree.find(node)
    if found == None:
        print "No %s in file" % node
        found = []
    return found  

# Parse a xml file (specify the path)
def_file = "xml_file_name.xml"
try:
    dom = ET.parse(open(def_file, "r"))
    root = dom.getroot()
except:
    exit_err("Unable to open and parse input definition file: " + def_file)

# Parse to find the child nodes list of node 'myNode'
fwdefs = find_in_tree(root,"myNode")
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus