Python:XML

From wiki
Revision as of 14:02, 14 January 2018 by Hdridder (talk | contribs) (Created page with ";from xml.etree import ElementTree :Load XML-support ;tree = get_tree(filename) :Read the file into an XML-tree ;root = tree.getroot() :Get the tree root element object ;fo...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
from xml.etree import ElementTree
Load XML-support
tree = get_tree(filename)
Read the file into an XML-tree
root = tree.getroot()
Get the tree root element object
for element in root
Get the elements in root
element.tag
element.attrib
element.text
<tag attribname=attrib>text</tag>


#!/usr/bin/env python3

def usage():
    print ("Print XML tags, attributes and text")
    print ("Usage: "+__file__+" <xmlfile>")
    exit()
    return

import os
import sys
from xml.etree import ElementTree

def main():
    if len(sys.argv) == 2:
        filename = sys.argv[1]
    else:
        usage()
    tree = get_tree(filename)
    root = tree.getroot()
    get_all(root)
    print(root)
    return
    
def get_all(element,prefix=""):
    prefix = prefix+"\t"
    for child in element:
        print (prefix,child.tag,child.attrib,child.text)
        get_all(child,prefix)
    return
            
def get_tree(filename):
    if os.path.isfile(filename):
        #with open(filename, 'r') as f:
         #   tree = ElementTree.parse(f)
       tree = ElementTree.parse(filename) 
    else:
        usage() 
    return(tree)
    
main()