[英]Adding an attribute to a root element using an XSL file
我正在努力做一些看起来很简单的事情。 我想使用 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 文件如下,并使用此逻辑:
复制所有元素
仅修改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>
预期的 XML output 应该是:
<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 顶部的不同元素具有属性...
提前感谢您对这个小问题的帮助!
编辑:我在下面添加解决方案。 马丁回答的关键是复制并应用模板。
<?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>
问候, 埃里亚托克
做一个浅拷贝,添加属性并处理孩子:
<xsl:template match="row[not(@*)]">
<xsl:copy>
<xsl:attribute name="tableName">passage</xsl:attribute>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
这也改变了构造属性值的方式,您的示例建议您需要一个常量值。
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.