使用XSL文件为XML的row元素添加属性遇问题求助
问题:为XML中特定元素添加属性的XSL转换报错解决
问题背景
我正被一件看似简单的事困扰:想通过XSL转换,给XML文件里所有特定类型的元素添加属性。
源XML示例
<?xml version="1.0" encoding="UTF-8"?> <row> <Item_1>110000001</Item_1> <Item_2>700555608</Item_2> <Item_3>1</Item_3> <Item_4>2005-12-07</Item_4> <age_passage_a>21</age_passage_a> <age_passage_m>217</age_passage_m> <age_passage_j>6669</age_passage_j> <date_entree>2022-08-08 01:25:00</date_entree> <date_naissance>2003-12-07</date_naissance> </row>
源文件若包含多个<row>元素,会被<root>元素包裹。
最初的XSL代码
我的XSL逻辑是:
- 复制所有元素
- 仅修改无属性的
<row>元素并添加属性
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> <xsl:output encoding="UTF-8" indent="yes" method="xml" version="1.0" /> <xsl:template match="node() | @*"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <xsl:template match="row[not(@*)]"> <xsl:attribute name="tableName"> <xsl:value-of select="passage"/> </xsl:attribute> </xsl:template> </xsl:stylesheet>
预期输出
<row tableName="passage"> <Item_1>110000001</Item_1> <Item_2>700555608</Item_2> <Item_3>1</Item_3> ... </row> <row tableName="passage"> <Item_1>110000001</Item_1> <Item_2>700555608</Item_2> <Item_3>1</Item_3> ... </row>
遇到的问题
执行转换时报错,提示无法为文档级元素添加属性。我对此困惑,因为XML顶层元素本身是可以有属性的。
解决方案
关键在于复制元素并应用模板,修正后的XSL代码如下:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output encoding="UTF-8" indent="yes" method="xml" version="1.0" /> <xsl:param name="TABLE_NAME">passage</xsl:param> <xsl:template match="node() | @*"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <xsl:template match="row[not(@*)]"> <xsl:copy> <xsl:attribute name="tableName"> <xsl:value-of select="$TABLE_NAME"/> </xsl:attribute> <xsl:apply-templates/> </xsl:copy> </xsl:template> </xsl:stylesheet>
内容的提问来源于stack exchange,提问作者Eriatolc
相关产品推荐
相关产品推荐

