Click here to Skip to main content
12,395,388 members (70,698 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: Python
#!/usr/bin/python
 
# Import
import xml.etree.ElementTree as ET
import sys
 

def removeNS(tag) :
    if tag.find('}') == -1 :
        return tag
    else:
        return tag.split('}', 1)[1]
 
def linearize(el, path) :
 
    # Print text value if not empty
    text = el.text.strip()
    if text == "" :
        print path  
    else :
 
        # Several lines ?
        lines = text.splitlines()
        if len(lines) > 1 :
            lineNb=1
            for line in lines :
                print path + "[line %d]=%s " % (lineNb, line)
                lineNb += 1
        else :
            print path + "=" + text
    
 
    # Print attributes
    for name, val in el.items() :
        print path + "/@" + removeNS(name) + "=" + val
 
    # Counter on the sibbling element names
    counters = {}
 
    # Loop on child elements
    for childEl in el :
 
        # Remove namespace
        tag = removeNS(childEl.tag)
 
        # Tag name already encountered ?
        if counters.has_key(tag) :
            counters[tag] += 1
            # Number it
            numberedTag = tag + "[" + str(counters[tag]) + "]"
        else :
            counters[tag] = 1
            numberedTag = tag
 
        # Print child node recursively
        linearize(childEl, path + '/' + numberedTag)
 
# Main 
def process(stream, prefix) :
 
    # Parse the XML
    tree = ET.parse(stream)
 
    # Get root element
    root = tree.getroot()
 
    # Linearize
    linearize(root, prefix + "//" + removeNS(root.tag))
 

# Each argument is a file
args = sys.argv[1:]
 
# Loop on files
for filename in args :
 
    # Open the file
    file = open(filename)
    
    # If we process several files, prefix each one with its path
    if len(args) > 1 :
        prefix = filename + ":"
    else:
        prefix = ""
 
    # Process it
    process(file, prefix)
 
# No input file ? => Proces std input
if len(args) == 0 :
    process(sys.stdin, "") 
Posted 25-Jan-11 8:35am
Comments
SAKryukov 25-Jan-11 14:41pm
   
Thank you for sharing your code.
Do you have any questions?
rahil karedia 27-Jan-11 12:38pm
   
i need code for creating ASCII engine in C++ ?

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

These forums are for asking questions about coding issues, not for posting code snippets. If you want to post a code snippet for others to use, post a new Tip & Trick under the Articles menu.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160721.1 | Last Updated 25 Jan 2011
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100