2015-06-21 67 views
0

我有一个具体的要求,我需要更改当前元素的属性值与前面的兄弟节点值。如何将属性值更改为前兄弟值

当前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> 

我能够改变日当我对值进行硬编码时,属性中的e值不作为变量。

+0

你的XML不能很好地形成张贴,一些标签不具备相应的结束标记:'COM:SubCateTypeCode' VS'COM:SubCatTypeCode','COM:ComCode' VS'COM:ComponentCode'。请修复该问题 – har07

回答

1

假设你有一个合式 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元素。

+0

谢谢。这就像一个魅力! –