如何通过XSLT从HTTP JSON端点获取数据并完成转换?
在XSLT中获取HTTP端点JSON数据并转换的问题解决
问题场景
需要从HTTP端点获取JSON数据,并在XSLT转换中使用其值。示例JSON数据如下:
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
原XSLT代码:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0"> <xsl:output method="xml" encoding="UTF-8" indent="yes"/> <xsl:template match="*"> <person> <xsl:variable name="title" select="json-to-xml(document('https://jsonplaceholder.typicode.com/todos/1'))/title"/> <xsl:element name="Field"> <xsl:attribute name="name">Title</xsl:attribute> <xsl:attribute name="value"> <xsl:value-of select="$title"/> </xsl:attribute> </xsl:element> </person> </xsl:template> </xsl:stylesheet>
执行时出现错误:
错误信息:Error: org.xml.sax.SAXParseException; systemId: https://jsonplaceholder.typicode.com/todos/1; lineNumber: 1; columnNumber: 1; 序言中不允许有内容。
错误原因
document()函数用于加载并解析XML文档,而HTTP端点返回的是JSON数据,XML解析器尝试将JSON当作XML解析时,会因为JSON语法不符合XML规则(比如开头的{并非XML声明或根元素),从而抛出“序言中不允许有内容”的错误。
修正后的XSLT代码
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0"> <xsl:output method="xml" encoding="UTF-8" indent="yes"/> <xsl:template match="*"> <person> <!-- 获取JSON原始文本内容 --> <xsl:variable name="json-text" select="unparsed-text('https://jsonplaceholder.typicode.com/todos/1')"/> <!-- 将JSON转换为XML结构 --> <xsl:variable name="json-xml" select="json-to-xml($json-text)"/> <!-- 从转换后的XML中提取title值 --> <xsl:variable name="title" select="$json-xml/*:map/*:string[@key='title']"/> <xsl:element name="Field"> <xsl:attribute name="name">Title</xsl:attribute> <xsl:attribute name="value" select="$title"/> </xsl:element> </person> </xsl:template> </xsl:stylesheet>
关键说明
- 使用
unparsed-text()函数读取HTTP端点返回的原始JSON字符串,该函数专门用于处理非XML文本内容。 json-to-xml()会将JSON转换为固定结构的XML:根元素为<map>(带默认命名空间),每个JSON键值对对应一个带key属性的子元素,比如字符串类型的title对应<string key="title">delectus aut autem</string>。- 提取值时需匹配正确的XML路径,使用
*:前缀可忽略命名空间匹配问题,避免因命名空间声明带来的路径错误。
内容的提问来源于stack exchange,提问作者Gopinath
相关产品推荐
相关产品推荐

