如何用XSL正确转换MySQL查询输出的XML至目标格式?
MySQL查询XML转XSLT的问题解决
问题背景
原始MySQL输出XML
<?xml version="1.0"?> <resultset statement="SELECT product_id, product_price FROM products WHERE 1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <row> <field name="product_id">123456</field> <field name="product_price">12.55</field> </row> <row> <field name="product_id">9999</field> <field name="product_price">4.95</field> </row> </resultset>
注:原始XML存在语法错误(field标签属性未闭合),已修正为合法格式
当前使用的XSLT脚本
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="resultset"> <products> <vendor>vendor_123</vendor> <timestamp></timestamp> <xsl:apply-templates/> </products> </xsl:template> <xsl:template match="row"> <product> <product_code custid="{field[@name='product_id']}"> </product_code> <price> <xsl select="{field[@name='product_price']}"/> </price> </product> </xsl:template> </xsl:stylesheet>
当前错误转换结果
<?xml version="1.0"?> <products> <vendor>vendor_123</vendor> <timestamp/> <product> <product_code custid="123456"/> <price> <xsl select="12.55"/> </price> </product> <product> <product_code custid="9999"/> <price> <xsl select="4.95"/> </price> </product> </products>
期望转换结果
<?xml version="1.0"?> <products> <vendor>vendor_123</vendor> <timestamp/> <product> <product_code>123456</product_code> <price>12.55</price> </product> <product> <product_code>9999</product_code> <price>4.95</price> </product> </products>
触发的错误信息
使用<xsl:value-of select="{field[@name='product_price']}"/>时出现:
XPath error: Invalid expression {field[@name='product_price']} compilation error: file script.xslt line 19 element value-of xsl:value-of : could not compile select expression '{field[@name='product_price']}'
错误原因
{...}是属性值模板的专属语法,仅用于在XML属性中插入XPath表达式结果。而<xsl:value-of>的select属性需要直接传入纯XPath表达式,额外包裹大括号会被判定为无效语法。此外原代码中还存在拼写错误:<xsl select>应为<xsl:value-of>。
正确的XSLT代码
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="resultset"> <products> <vendor>vendor_123</vendor> <timestamp></timestamp> <xsl:apply-templates/> </products> </xsl:template> <xsl:template match="row"> <product> <!-- 将product_id的值作为product_code的文本内容输出 --> <product_code> <xsl:value-of select="field[@name='product_id']"/> </product_code> <!-- 正确使用xsl:value-of,直接传入XPath表达式 --> <price> <xsl:value-of select="field[@name='product_price']"/> </price> </product> </xsl:template> </xsl:stylesheet>
关键修改说明
- product_code元素:移除原有的
custid属性,改用<xsl:value-of>将product_id的值作为元素文本内容输出。 - price元素:修正元素拼写错误,同时去掉XPath表达式外的大括号,直接传入
field[@name='product_price']作为select参数。
内容的提问来源于stack exchange,提问作者user3358102
相关产品推荐
相关产品推荐

