Frage

So, I've seen a lot of answers that target this question, but they don't explicitly state how to adjust the namespace prefix when it changes throughout the span of the XML document.

What I have:

<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
    <ns0:Description xmlns:ns0="http://purl.org/NET/FOO">
    </ns0:Description>
</rdf:RDF>

What I want:

<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
    <rdf:Description rdf:about="http://purl.org/NET/FOO">
    </rdf:Description>
</rdf:RDF>

To clarify, I want the child SubElement's xmlns:rdfs to be rdf:about.

What used to work in Python2.5:

rdf_description = SubElement(
    root,
    '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description',
    {'rdf:about':vocab_namespace}
)

What I've tried in Python2.7:

register_namespace('rdf', 'rdf:about')
rdf_description = SubElement(
    root,
    '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description',
    nsmap={'rdf': rdf_url}
)

... well I've tried that and permutations of such too long to list (this is how I currently have it), but I can't seem to shift the bits how I need them.

If a true lxml ninja could step down from their palace of pleasure and instruct this newb, I would be forever grateful.

War es hilfreich?

Lösung

Does this work for you?

RDFNS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
root = lxml.etree.Element('{%s}RDF' % RDFNS, nsmap={'rdf': RDFNS})
rdf_description = lxml.etree.SubElement(
    root,
    '{%s}Description' % RDFNS,
    {"{%s}about" % RDFNS: "http://purl.org/NET/FOO"})

Checking output:

>>> print lxml.etree.tostring(root, pretty_print=True)
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <rdf:Description rdf:about="http://purl.org/NET/FOO"/>
</rdf:RDF>

>>> 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top