【发布时间】:2014-04-17 21:21:23
【问题描述】:
下面是我的起始 XML:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:something-well-formed">
<child1 attr1="a" attr2="b">
<child1 attr1="c" attr2="b"/>
</child1>
<child3/>
<child1 attr1="d" attr2="b">
<child2 attr1="e" attr2="b"/>
</child1>
</root>
在上面运行转换后,我得到了一个中间结果 xml,其中所有属性都被剥离了,在这种情况下,是从 child1 节点:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:something-well-formed">
<child1>
<child1/>
</child1>
<child3/>
<child1>
<child2 attr1="e" attr2="b"/>
</child1>
</root>
我想做的是对上面生成的中间结果进行转换,以创建一个类似于以下示例的 xml 文档,在这种情况下,我可以指定第 n 个实例, child1 并相应地设置它的属性:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:something-well-formed">
<child1 attr1="something", attr2="something else">
<child1/>
</child1>
<child3/>
<child1>
<child2 attr1="e" attr2="b"/>
</child1>
</root>
这是我尝试使用的示例 xslt:
<xsl:param name="element" />
<xsl:param name="attributes" />
<xsl:param name="nodeNumber"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="*[name(.)=$element]">
<xsl:copy>
<xsl:apply-templates select="@*" />
<!-- Splits into separate key/value pairs elements -->
<xsl:variable name="attributesSeq" select="tokenize($attributes, ';')" />
<xsl:for-each select="$attributesSeq">
<xsl:variable name="attributesSeq" select="tokenize(., ',')" />
<xsl:variable name="key"
select="replace($attributesSeq[1], '"', '')" />
<xsl:variable name="value"
select="replace($attributesSeq[2], '"', '')" />
<xsl:attribute name="{$key}">
<xsl:value-of select="$value" />
</xsl:attribute>
</xsl:for-each>
<xsl:apply-templates select="node()" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
问题是上面的 xslt 将“attributes”参数中的内容复制到 child1 的每个实例,而我的目标是将“attributes”参数的内容复制到 child1 的第 n 个实例。
其他问题:我希望将节点名称参数化为我选择传入的任何节点名称的第 n 个实例。上面的示例使用 child1,但它应该适用于任何节点名称(即 child3, child37 等)。
感谢您的帮助!
【问题讨论】: