You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将XQuery返回的PyXdmValue转换为Python原生类型?

将PyXdmValue转换为Python原生类型(Saxon-Che)

PyXdmValue是Saxon-Che返回的XDM结果容器,要转成Python原生类型,分以下几种场景处理:

1. 单一原子值(字符串、数字、布尔值等)

如果你的XQuery返回单个原子值,先通过item_at(0)获取第一个结果项,再调用to_python()转换:

from saxonche import *

with PyXQueryProcessor(license=False) as proc:
    with proc.new_xquery_processor() as q:
        q.set_context(file_name="data.xml")
        qry_str = "//book/price/text()"  # 示例:获取单个价格
        res = q.run_query_to_value(query_text=qry_str)
        native_price = res.item_at(0).to_python()  # 得到Python float/int

2. 序列值(多个原子值)

如果返回多个结果,利用PyXdmValue的迭代器接口,遍历每个项并转换:

from saxonche import *

with PyXQueryProcessor(license=False) as proc:
    with proc.new_xquery_processor() as q:
        q.set_context(file_name="data.xml")
        qry_str = "//book/title/text()"  # 示例:获取所有书名
        res = q.run_query_to_value(query_text=qry_str)
        native_titles = [item.to_python() for item in res]  # 得到Python列表

3. 复杂XML节点转结构化Python类型(字典/列表)

如果要处理复杂的XML节点(比如嵌套元素),最便捷的方式是在XQuery中先将结果序列化为JSON,再用Python的json模块解析:

from saxonche import *
import json

with PyXQueryProcessor(license=False) as proc:
    with proc.new_xquery_processor() as q:
        q.set_context(file_name="data.xml")
        # XQuery中序列化结果为JSON,配置节点转数组/对象的规则
        qry_str = """
        serialize(
            //book,
            map{
                'method':'json', 
                'indent':true(), 
                'array-node-kind':'array',
                'suppress-indentation':false()
            }
        )
        """
        res = q.run_query_to_value(query_text=qry_str)
        json_str = res.item_at(0).to_python()
        native_books = json.loads(json_str)  # 得到Python字典/列表结构

关键说明

  • to_python()会自动映射XDM类型到Python原生类型:XDM字符串→str、整数→int、布尔值→bool、日期→datetime.datetime等
  • 直接遍历PyXdmValue即可获取所有结果项,无需手动处理长度
  • 对于节点类型,to_python()返回的是XML片段字符串,因此结构化场景优先用JSON序列化方案

内容的提问来源于stack exchange,提问作者N Raghu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 18:10:11