Using xml.xpath question.

Paul Boddie paul at
Fri Jul 11 10:57:39 CEST 2003

bvelkur at (0wl) wrote in message news:<de5c7cc0.0307101347.2c707bf8 at>...
> Hi,
> I am trying to get the value of child from  
> xmlstr = """<p:root xmlns:p=""><p:child
> DataType="String">Hellpppp</p:child></p:root>"""
> using 
> doc=parseString(xmlstr)
> nodeList = xml.xpath.Evaluate("/p:root/p:child/text()", doc)
> and am getting the following exception:
> xml.xpath.RuntimeException: Undefined namespace prefix: "p".

The problem is that the XPath query engine doesn't know what the
prefix "p" is, and it won't automatically deduce it from your XML
document. In other words, the prefixes used in your query are
effectively independent from those used in your document, although
this does give you the luxury of changing either your query or your
document without having to go through the other adjusting the prefixes
to match.

Try this:

>>> c = xml.xpath.Context.Context(doc)
>>> c.setNamespaces({"p" : ""})

This makes a context and then adds the definition of the prefix for
the XPath query engine. I think xml.xpath.CreateContext(doc) may be
more appropriate, but I always use the above style. Also, you could
probably specify the prefix/namespace definitions in the Context
constructor, but this is just as easy.

>>> e = xml.xpath.Compile("/p:root/p:child/text()")

I compile the expression in order to allow the context to be used. We
need a context because there apparently isn't any way of specifying
the prefix/namespace definitions directly in an Evaluate call.
Therefore, we have to set up a context first to contain those

>>> e.evaluate(c)
[<DOM Text node "Hellpppp">]

Yes, it works! ;-)


More information about the Python-list mailing list