Using xml.xpath question.
0wl
bvelkur at yahoo.com
Fri Jul 11 16:30:55 EDT 2003
Works like a charm!!!!!
My Ignorance shines bright.... :-).
Anywhere I can read about this stuff..
Thanks
--Bipin.
paul at boddie.net (Paul Boddie) wrote in message news:<23891c90.0307110057.bbe91e3 at posting.google.com>...
> bvelkur at yahoo.com (0wl) wrote in message news:<de5c7cc0.0307101347.2c707bf8 at posting.google.com>...
> > Hi,
> >
> > I am trying to get the value of child from
> >
> > xmlstr = """<p:root xmlns:p="http://tempuri.org/string"><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" : "http://tempuri.org/string"})
>
> 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
> definitions.
>
> >>> e.evaluate(c)
> [<DOM Text node "Hellpppp">]
>
> Yes, it works! ;-)
>
> Paul
More information about the Python-list
mailing list