2013-03-12 15 views
5

Ho scritto uno script che stampa tutti i file .xml nella directory corrente in formato xml, ma non riesco a capire come aggiungere gli attributi xmlns al top- tag di livello. L'uscita che voglio ottenere è:Python: aggiunta degli attributi dello schema xml con lxml

<?xml version='1.0' encoding='utf-8'?> 
<databaseChangeLog 
     xmlns="http://www.host.org/xml/ns/dbchangelog" 
     xmlns:xsi="http://www.host.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="www.host.org/xml/ns/dbchangelog"> 

    <include file="cats.xml"/> 
    <include file="dogs.xml"/> 
    <include file="fish.xml"/> 
    <include file="meerkats.xml"/> 

</databaseChangLog> 

Tuttavia, qui è l'uscita sto ottenendo:

<?xml version='1.0' encoding='utf-8'?> 
<databaseChangeLog> 
    <include file="cats.xml"/> 
    <include file="dogs.xml"/> 
    <include file="fish.xml"/> 
    <include file="meerkats.xml"/> 
</databaseChangLog> 

Ecco il mio script:

import lxml.etree 
import lxml.builder 
import glob 

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

# grab all the xml files 
files = [DOC(file=f) for f in glob.glob("*.xml")] 
the_doc = ROOT(*files) 

str = lxml.etree.tostring(the_doc, pretty_print=True, xml_declaration=True, encoding='utf-8') 

print str 

ho trovato un po ' esempi online di impostazione esplicita degli attributi dello spazio dei nomi, here e here, ma per essere onesti sono andati un po 'in testa perché sono appena agli inizi. C'è un altro modo per aggiungere questi attributi xmlns al tag databaseChangeLog?

risposta

8
import lxml.etree as ET 
import lxml.builder 
import glob 

dbchangelog = 'http://www.host.org/xml/ns/dbchangelog' 
xsi = 'http://www.host.org/2001/XMLSchema-instance' 
E = lxml.builder.ElementMaker(
    nsmap={ 
     None: dbchangelog, 
     'xsi': xsi}) 

ROOT = E.databaseChangeLog 
DOC = E.include 

# grab all the xml files 
files = [DOC(file=f) for f in glob.glob("*.xml")] 

the_doc = ROOT(*files) 
the_doc.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)] = 'www.host.org/xml/ns/dbchangelog' 

print(ET.tostring(the_doc, 
        pretty_print=True, xml_declaration=True, encoding='utf-8')) 

rendimenti

<?xml version='1.0' encoding='utf-8'?> 
<databaseChangeLog xmlns:xsi="http://www.host.org/2001/XMLSchema-instance" xmlns="http://www.host.org/xml/ns/dbchangelog" xsi:schemaLocation="www.host.org/xml/ns/dbchangelog"> 
    <include file="test.xml"/> 
</databaseChangeLog> 
+0

che ha funzionato, grazie mille! Sapresti come formattare l'output in modo simile a ciò che è nell'output desiderato sopra? Ho pensato che pretty_print potesse essere d'aiuto, ma non sembra esserci d'aiuto :( – user1420913

+0

Scusa, non conosco un modo efficace per farlo – unutbu

+0

Nessun problema, grazie per il tuo aiuto :) – user1420913

Problemi correlati