django postgres xpath xml arrays

Having a xml field in your postgres database table, you may want to match something with xpath. Unfortunately the result of the match is an ARRAY, and the django.db.backends.postgresql_psycopg2 engine does not convert it properly to a list of ElementTree's.

But, this can be changed:

import xml.etree.ElementTree as ET
from psycopg2.extensions import new_type, register_type
from psycopg2.extensions import STRINGARRAY
 
import psycopg2
def cast_xml_array(value, cur):
	if value is None: 
		return []
	elements = STRINGARRAY(value,cur)
	return [ET.fromstring(i) for i in elements]
 
 
XML = new_type((143,), "XML[]", cast_xml_array)
register_type(XML)

This snippet registers a new type for the OID 143, which is xml[] for me. The result is converted to a list of strings using psycopg2's internal STRINGARRAY type, and this list of strings is converted to a list of ElementTrees.

Comments



2011/01/24/django_postgres_xpath_xml_arrays.txt · Last modified: 2011/01/24 23:32 by common
chimeric.de = chi`s home Creative Commons License Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0