简体   繁体   中英

How can I validate an XSLT template's logic against an XML schema?

An XSLT transform makes implicit assumptions about the structure of the XML that it is transforming. For example, the following:

<xsl:variable name="b"><xsl:value-of select="A/B"/></xsl:variable>

Assumes that the XML node "B" sits directly underneath "A", such as:

<A>
  <B>Hello</B>
<\A>

If the XML format has changed, and becomes:

<A>
  <AA>
    <B>Hello</B>
  </AA>
<\A>

The XSLT will now fail to find node B, and will assume that the node hadn't been specified in this case (which would be a valid option).

I had assumed that it would be possible to specify the XML schema that the XSLT is attempting to transform, and if the XSLT ever referenced a node that the schema didn't recognise, a validation error would be raised. However, I can't seem to find this implementation ( https://www.ibm.com/developerworks/library/x-schemaxslt/index.html appears to mention only validating the input XML and the generated XML - not the XSLT itself).

[Although an approach might be to create a XML schema of what the XSLT is expecting, and then compare the input XML against it, I have 100's of XSLTs at different versions, so this is impractical. It is simple, however, to create an XSD of the input and ask the XSLT if it is OK with that.]

This is what schema-aware processing in XSLT 2.0/3.0 is designed to achieve.

In the match pattern of a template rule, you have to declare that you are only going to use it to process schema-valid elements:

<xsl:template match="schema-element(invoice)">
 ...
</xsl:template>

or in XSLT 3.0 you can declare that all the template rules in a mode are designed to handle schema-valid input:

<xsl:mode typed="strict"/>

and then if you use a path that can't exist according to the schema, for example

<xsl:template match="schema-element(invoice)">
 <xsl:apply-templates select="customer-detials"/>
</xsl:template>

the XSLT processor will tell you about it. You have to tell the XSLT processor where to find the schema using an <xsl:import-schema> declaration.

Schema-awareness is a vastly underused feature of the language. It takes a bit of effort up-front to take advantage of it, and it can sometimes be a bit of a hassle with "false positive" error messages, but once you get the hang of it, it can catch a great number of simple user errors that would otherwise take hours to debug. In some cases schema-awareness can also aid performance, by reducing the amount of the source document that needs to be searched, and by avoiding repeated datatype conversions -- but better static error checking is the main benefit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM