mckbrd
mckbrd

Reputation: 1077

Parse XML where an element prefix is defined in the same element

I have an XML file with an element which looks like this:

<wrapping_element>
    <prefix:tag xmlns:prefix="url">value</prefix:tag>
</wrapping_element>

I want to get this element, so I am using lxml as follows:

wrapping_element.find('prefix:tag', wrapping_element.nsmap)

but I get the following error: SyntaxError: prefix 'prefix' not found in prefix map because prefix is not defined before reaching this element in the XML.

Is there a way to get the element anyway?

Upvotes: 0

Views: 1416

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52848

Like mentioned in the comments, you could use local-name() to circumvent the namespace, but it's easy enough to just handle the namespace directly in the xpath() call...

from lxml import etree

tree = etree.parse("input.xml")

wrapping_element = tree.xpath("/wrapping_element")[0]
tag = wrapping_element.xpath("x:tag", namespaces={"x": "url"})[0]

print(etree.tostring(tag, encoding="unicode"))

This will print...

<prefix:tag xmlns:prefix="url">value</prefix:tag>

Notice I used the prefix x. The prefix can match the prefix in the XML file, but it doesn't have to; only the namespace URIs need to match exactly.

See here for more details: http://lxml.de/xpathxslt.html#namespaces-and-prefixes

Upvotes: 1

Related Questions