使用xslt使用算术运算更改属性值

时间:2014-11-27 00:17:53

标签: xslt xpath

我正在尝试使用xslt / xpath 1.0绑定xml属性的值。在此示例中,它将是m_m元素上的id属性。

<blart>
   <m_data>
      <m_m name="arggg" id="99999999" subs="asas"/>
   </m_data>
   <m_data>
      <m_m name="arggg" id="99" subs="asas"/>
   </m_data>
</blart>

如果id大于20000则设置为20000.我有以下xslt。我知道它选择了正确的节点和属性。它显然只是输出20000.我意识到我应该有一些xpath逻辑,但我很难开发它。我对xpath和xslt的了解有一些大漏洞。如果你能指出我正确的方向帮助我理解我应该做什么,我会非常感激。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match ="m_data/m_m/@id[.&gt; 20000]">20000 </xsl:template>
</xsl:stylesheet> 

预期输出为

<blart>
   <m_data>
      <m_m name="arggg" id="20000" subs="asas"/>
   </m_data>
   <m_data>
      <m_m name="arggg" id="99" subs="asas"/>
   </m_data>
</blart>

3 个答案:

答案 0 :(得分:2)

您可以使用以下XSLT为您想要更改的属性提供灵活性,并保留其他所有内容:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match ="m_data/m_m/@id[. &gt; 20000]">
    <xsl:attribute name="id">20000</xsl:attribute>
</xsl:template>
</xsl:stylesheet>

答案 1 :(得分:2)

你为什么不试试:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match ="m_m/@id[. > 20000]">
    <xsl:attribute name="id">20000</xsl:attribute>
</xsl:template>

</xsl:stylesheet>

答案 2 :(得分:1)

注意:自从我发布此消息后,提供了更好的答案(请参阅herehere)。所以我不会删除这个,因为它被接受了,但公平地说,为了质量,我应该鼓励你提出上述两个答案,以便他们在这个问题上脱颖而出。


这个怎么样:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="m_m">
 <m_m>
  <xsl:copy-of select="@*" />
  <xsl:if test="@id &gt; 20000">
   <xsl:attribute name="id">20000</xsl:attribute>
  </xsl:if>
 </m_m>
</xsl:template>

<xsl:template match="m_data">
 <m_data>
  <xsl:apply-templates select="m_m" />
 </m_data>
</xsl:template>

<xsl:template match="/blart">
 <blart>
  <xsl:apply-templates select="m_data" />
 </blart>
</xsl:template>

</xsl:stylesheet>
相关问题