【问题标题】:Add element to a specific xpath using xslt使用 xslt 将元素添加到特定的 xpath
【发布时间】:2015-05-22 01:35:28
【问题描述】:

我想实现以下目标。

这是一个示例 XML:

<?xml version="1.0" encoding="iso-8859-1"?>
<database>
    <rad>
        <timeout> 45 </timeout>
    </rad>
    <tac>
        <timeout> 70 </timeout>
    </tac>    
</database>

1) 使用 XSLT 我想检查 /database/rad/timeout 值是否大于 30(在本例中为 45),将其更改为 30。

2) 添加新标签如下:

<warnings>
  <warning>Time out of RAD changed.</warning>
</warnings>

所以输出的 XML 应该包含以下内容:-

    <?xml version="1.0" encoding="iso-8859-1"?>
    <database>
        <rad>
            <timeout> 45 </timeout>
        </rad>
        <tac>
            <timeout> 70 </timeout>
        </tac>
     <warnings>
      <warning>Time out of RAD changed.</warning>
    </warnings>   
    </database>

可能存在很多这样的条件。我能够完成第一部分:-

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

    <xsl:template match="/database/rad/timeout">
        <timeout>
                <xsl:choose>
                    <xsl:when test=". > 30">30</xsl:when>
                    <xsl:otherwise><xsl:value-of select="."/></xsl:otherwise>
                </xsl:choose>
        </timeout>
    </xsl:template>
        <!-- ignore text content of nodex -->
    <xsl:template match="text()" />
    </xsl:stylesheet>

但是对于第二部分,我不确定从哪里开始,任何提示将不胜感激。谢谢。

【问题讨论】:

  • "如果 /database/rad/timeout 值大于 30 ... 将其更改为 30。" 您的输出显示为 45,而您的 XSLT 将其设为 100。那就是令人困惑。

标签: xml xslt xpath


【解决方案1】:

这样怎么样?

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="rad[timeout > 30]">
    <xsl:copy>
        <timeout>100</timeout>
    </xsl:copy>
    <warnings>
        <warning>Time out of RAD changed.</warning>
    </warnings>
</xsl:template>

</xsl:stylesheet>

【讨论】:

  • 这是个好主意,尽管它会将&lt;warnings&gt; 元素放在输出中的&lt;tac&gt; 元素之前。我想知道 OP 是否可以。
  • 谢谢,虽然我想在最后发出警告。
  • @michael.hor257k:实际上,这可能对我不起作用,因为错误/警告可能会从多个地方发出,我希望它们都显示为: RAD 超时已更改。ABC 超时已更改。。有没有办法做到这一点。
  • @user2766839 通过匹配database 元素而不是rad,我可以轻松地将警告移至末尾。但是,您添加的评论:“错误/警告可能从多个地方发出”表明情况比您的问题让我们相信的更复杂,我不确定我是否理解完全。请编辑您的问题并澄清 - (添加更多场景)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
相关资源
最近更新 更多