I'm working with an XQuery on an XML file and need the output in a Python-native format. Following the documentation, I tried executing the code below, however, the output I'm getting is in <class 'saxonche.PyXdmValue'>, and I'm struggling to convert it into native Python data types.
from saxonche import *
P = PyXQueryProcessor(license=False)
Q = P.new_xquery_processor()
Q.set_context(file_name="data.xml")
res = Q.run_query_to_value(query_text=qry_str)
How do I convert the response type(<class 'saxonche.PyXdmValue'>) to python native containers?
As I said in a comment, a
PyXdmValuerepresents an XDM 3.1 sequence of XDM 3.1 items which can be of various, rather different types, like XDM nodes, XDM atomic values (of different type like string, boolean, various numeric types, various date/dateTime/duration types) and function items (including maps and arrays).So depending on your query you need to write code taking the result structure and the type of the items into account.
To give you one example, the query
computes the average population for a city in a country and returns the result as an XDM map with
xs:stringkey values andxs:doubleproperty values.An example input file would be e.g.
In Python you could access the returned PyXdmMap as the first item
[0]of thePyXdmValueand for instance use dictionary comprehension to convert that PyXdmMap into a Python dictionary:Output is e.g.
To give you a different example, where a sequence of XML elements is returned and then, depending on your needs, can be converted into a Pyton list of the string value or the element serialization:
Output is e.g.