2016-10-22 3 views
0

Ich brauche xml zu erzeugen, die wie folgt aussieht:Generierung von XML mit LXML - Attribut Namespace

<definitions xmlns:ex="http://www.example1.org" xmlns="http://www.example2.org"> 
    <typeRef xmlns:ns2="xyz">text</typeRef> 
</definitions> 

Mein Code sieht wie folgt aus:

class XMLNamespaces: 
    ex = 'http://www.example1.org' 
    xmlns = 'http://www.example2.org' 

root = Element('definitions', xmlns='http://www.example2.org', nsmap = {'ex':XMLNamespaces.ex}) 
type_ref = SubElement(root, 'typeRef') 
type_ref.attrib[QName(XMLNamespaces.xmlns, 'ns2')] = 'xyz' 
type_ref.text = 'text' 

tree = ElementTree(root) 
tree.write('filename.xml', pretty_print=True) 

Das Ergebnis sieht so aus:

<definitions xmlns:ex="http://www.example1.org" xmlns="http://www.example2.org"> 
    <typeRef xmlns:ns0="http://www.example2.org" ns0:ns2="xyz">text</typeRef> 
</definitions> 

Also hier ist meine Frage:

Wie man das Attribut aussehen lässt xmlns: ns2 = "xyz" statt xmlns: ns0 = "http://www.example2.org" ns0: ns2 = "xyz"?

Antwort

1

Führen Sie einfach den gleichen Prozess wie Ihr öffnendes Element, wo Sie das Namespace-Wörterbuch mit Nsmap Argument definiert. Beachten Sie die hinzugefügte Variable in Ihrem Klassenobjekt:

from lxml.etree import * 

class XMLNamespaces: 
    ex = 'http://www.example1.org' 
    xmlns = 'http://www.example2.org' 
    xyz = 'xyz' 

root = Element('definitions', xmlns='http://www.example2.org', nsmap={'ex':XMLNamespaces.ex}) 
type_ref = SubElement(root, 'typeRef', nsmap={'ns2':XMLNamespaces.xyz}) 
type_ref.text = 'text' 

tree = ElementTree(root) 
tree.write('filename.xml', pretty_print=True) 

# <definitions xmlns:ex="http://www.example1.org" xmlns="http://www.example2.org"> 
# <typeRef xmlns:ns2="xyz">text</typeRef> 
# </definitions> 
Verwandte Themen