Frage

I'm given a directory, and I have to write a python script that creates an xml file that includes all the .xml files in that directory.

For example, say /tmp/ contains the following xml files:

beans.xml
cakes.xml
donuts.xml

I'm trying to figure out how to write a script that creates the following xml:

<root>
   <include file="/tmp/beans.xml"/>
   <include file="/tmp/cakes.xml"/>
   <include file="/tmp/donuts.xml/>
</root>

This is what I've pieced together so far, but it overwrites the file tag each time so only donuts.xml is included

import lxml.etree
import lxml.builder
import glob
import os

E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.include

os.chdir("/tmp/")
for f in glob.glob("*.xml"):
    the_doc = ROOT(

    DOC(file=f)

)

print lxml.etree.tostring(the_doc, pretty_print=True)

This is the output of my script as it is right now:

<root>
    <include file="/tmp/donuts.xml"/>
</root>

How do I keep beans.xml and cakes.xml form being overwritten?

War es hilfreich?

Lösung

You are overwriting the_doc in each iteration. That's why your output has only one element. Try with this:

os.chdir("/tmp/")
files = [DOC(file=f) for f in glob.glob("*.xml")]
the_doc = ROOT(*files)
print lxml.etree.tostring(the_doc, pretty_print=True)

Andere Tipps

I don't know much about lxml, but reading the documentation leads to this solution:

import os
import glob
from lxml import etree

if __name__ == '__main__':
    root = etree.Element('root')
    os.chdir('/tmp')
    for filename in glob.glob('*.xml'):
        root.append(etree.Element('include', file=filename))

    print etree.tostring(root, pretty_print=True) # Or, print to a file if you wish
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top