[lxml-dev] Using the Xpath id function

Jim Washington jwashin at vt.edu
Wed Jul 2 19:24:07 CEST 2008


Jim Washington wrote:
> xml:id,  http://www.w3.org/TR/xml-id/ works OK, if you do not want to
> use a schema.  At least, it works with lxml 2.1.beta3.
> 
> from lxml import etree
> XML_NAMESPACE='http://www.w3.org/XML/1998/namespace'
> XML_PREFIX= '{%s}' % XML_NAMESPACE
> f = etree.Element('test')
> f.set(XML_PREFIX+'id','23455')
> etree.tostring(f)
> '<test xml:id="23455"/>'
> g = etree.SubElement(f,'test1')
> g.set(XML_PREFIX+'id','23456')
> f.xpath('id("23456")')
> [<Element test1 at 777520>]
> f.xpath('id("23455")')
> [<Element test at 7774c8>]
> 

A quick blunder fix:

The above works, but is not quite in accordance with the xml:id
specification.  Other XML processors may balk at the above.

The error in this case is that the value of xml:id attributes cannot
start with digits.

The concept works, but it is a bad example.

- Jim Washington



More information about the lxml-dev mailing list