我有一个特殊的要求,我需要用前面的同级节点值更改当前元素的属性值。
当前的XML
<com:row>
<com:new>
<com:Component ExcludeInd="false">
<com:CatTypeCode>35</com:CatTypeCode>
<com:SubCatTypeCode>055508</com:SubCatTypeCode>
<com:ComCode>1000</com:ComCode>
<com:VComponentCode>nbr</com:VComponentCode>
<com:Val Value="sometext">250</com:Val>
</com:Component>
</com:new>
</com:row>
XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:com="http://www.w3.org/2001/XMLSchema-instance">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="../com:Component/com:Val">
<xsl:element name="com:Val" namespace="http://www.w3.org/2001/XMLSchema-instance">
<xsl:variable name="myVar" select="preceding-sibling::com:VComponentCode"/>
<xsl:attribute name="ValueType"><xsl:value-of select="$myVar"/></xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
预期的XML
<com:row>
<com:new>
<com:Component ExcludeInd="false">
<com:CatTypeCode>35</com:CatTypeCode>
<com:SubCatTypeCode>055508</com:SubCatTypeCode>
<com:ComCode>1000</com:ComCode>
<com:VComponentCode>nbr</com:VComponentCode>
<com:Val Value="nbr">250</com:Val>
</com:Component>
</com:new>
</com:row>
当我对值进行硬编码时,可以更改属性中的值,但不能将其作为变量。
假设您具有格式正确的XML输入,则可以尝试以下XSL转换:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:com="http://www.w3.org/2001/XMLSchema-instance">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="com:Val/@Value">
<xsl:attribute name="Value">
<xsl:value-of select="parent::com:Val/preceding-sibling::com:VComponentCode"/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
简要说明 :
<xsl:template match="@* | node()">
:身份模板。该模板将匹配的元素和属性复制到输出XML中,就像在源XML中一样。
<xsl:template match="com:Val/@Value">
:覆盖元素Value
属性的标识模板com:Val
。代替复制属性以输出该模板,而是Value
使用从先前的同级com:VComponentCode
元素获取的值来创建新属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句