0

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?

4
  • I think the problem is rather that wrapping_element.nsmap is empty. I don't even find find in the documentation labyrinth, but there seems to be a method xpath too, maybe you can use it. Commented May 17, 2018 at 9:24
  • @ArndtJonasson The thing is, xpath requires a namespaces argument as find does. My problem is that I can't find a way to retrieve the namespace without the element nor the element without the namespace. Commented May 17, 2018 at 9:49
  • How about wrapping_element.xpath('/*/*[local-name()="tag"]')? Commented May 17, 2018 at 11:51
  • @ArndtJonasson Great! I used a relative path: wrapping_element.xpath('./*[local-name()="tag"]'), it's working perfectly. Thanks a lot! Commented May 17, 2018 at 12:06

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.