Welcome, guest | Sign In | My Account | Store | Cart

Builds a directory tree in XML format. Demonstrates how to use xml.dom.minidom to rapidly construct nested XML with multiple element types and attributes. Serves as a model for building model complex documents.

Python, 21 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import os, os.path
from xml.dom.minidom import Document

doc = Document()

def makenode(path):
    "Return a document node contains a directory tree for the path."
    node = doc.createElement('dir')
    node.setAttribute('name', path)
    for f in os.listdir(path):
        fullname = os.path.join(path, f)
        if os.path.isdir(fullname):
            elem = makenode(fullname)
        else:
            elem = doc.createElement('file')
            elem.setAttribute('name', f)
        node.appendChild(elem)
    return node

doc.appendChild(makenode('/pydev/scheme'))
print doc.toprettyxml()

Once, the document is built, it is easy to experiment with other XML tools for searching, altering, or storing the document: <pre>

Scan for files

for f in doc.getElementsByTagName('file'): print f.getAttribute('name')

Write the output to a file

destfile = open('mydir.xml', 'w') doc.writexml(destfile, addindent=' ', newl='\n') destfile.close() </pre>