java 如何从 XSLT 抛出异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13523750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:05:34  来源:igfitidea点击:

How can I throw an exception from XSLT?

javaxmlxslt

提问by Abin Manathoor Devasia

I want to throw an exception if one tag doesn't contain an attribute.

如果一个标签不包含属性,我想抛出异常。

采纳答案by Dimitre Novatchev

In addition to the correct answer of using <xsl:message terminate="yes"/>:

除了使用的正确答案<xsl:message terminate="yes"/>

  1. In XSLT 3.0 one can use the new instructions <xsl:try ...>and <xsl:catch ...>: http://www.w3.org/TR/xslt-30/#try-catch

  2. In XSLT 2.0 one can also use the standart XPath function error()to terminate the processing.

  1. 在 XSLT 3.0 中可以使用新指令<xsl:try ...><xsl:catch ...>http: //www.w3.org/TR/xslt-30/#try-catch

  2. 在 XSLT 2.0 中,还可以使用标准的 XPath 函数error()来终止处理。

Here is an example of using xsl:tryand xsl:catch:

下面是一个使用xsl:tryand的例子xsl:catch

<xsl:result-document href="out.xml">
  <xsl:variable name="result">
    <xsl:call-template name="construct-output"/>
  </xsl:variable>
  <xsl:try>
    <xsl:copy-of select="$result" validation="strict"/>
    <xsl:catch>
      <xsl:message>Warning: validation of result document failed:
          Error code: <xsl:value-of select="$err:code"/>
          Reason: <xsl:value-of select="$err:description"/>
      </xsl:message>
      <xsl:sequence select="$result"/>
    </xsl:catch>
  </xsl:try>
</xsl:result-document>

回答by Petr Kozelka

Use xsl:messagewith terminate="yes"to achieve effect similar to throwing an exception:

使用xsl:messagewithterminate="yes"达到类似抛出异常的效果:

<xsl:if test="(your condition)">
   <xsl:message terminate="yes">ERROR: Missing attribute XYZ under
      <xsl:value-of select="local-name()"/> !</xsl:message>
</xsl:if>

This causes the message to be sent to STDERR and terminate processing.

这会导致消息被发送到 STDERR 并终止处理。

BTW. this is heavily used in Schematronvalidation.

顺便提一句。这在Schematron验证中被大量使用。

回答by InfantPro'Aravind'

XSLT isn't meant for validation! it is meant for transformation .. (well XSLT stands for EXtensible Stylesheet Language Transformation)

XSLT 不用于验证!它用于转换..(XSLT 代表可扩展样式表语言转换)

If you want to validate hierarchy (that is your requirement) and validate the data .. then go for XSD! Extensible Schema Definition..

如果您想验证层次结构(这是您的要求)并验证数据.. 然后选择 XSD!可扩展架构定义..

here is a link reference to learn XSD

这是学习 XSD的链接参考

XML has to be validated against the XSD by the host code (C#, Java etc) The validation returns set of results. Success or fail with validation errors (if exist)..

XML 必须由主机代码(C#、Java 等)针对 XSD 进行验证。验证返回结果集。成功或失败并出现验证错误(如果存在)。