yas
yas

Reputation: 3620

XSLT performance when searching entire document for Id

I have an XML document with Id's attached to elements, for example:

<Section>
    <Field Id="1">... content ...</Field>
    <Field Id="2">... content ...</Field>
    <Section>
        <Field Id="5">... content ...</Field>
        <Field Id="6">... content ...</Field>
        <Section>
            <Field Id="10">... content ...</Field>
            <Field Id="20">... content ...</Field>
        ...
        </Section>
     ...
     </Section>
...
</Section>

The actual documents have many nested sections and fields. Is a search for a particular Id performed using an XPath expression such as:

 //Field[@Id=$vSearchId]

potentially an expensive operation? $vSearchId here represents a variable in XSL stylesheet holding the Id search for.

Are there more efficient ways to perform such a lookup, such as building an index? I looked at xsl:key but I wasn't sure how to use it for a search across the entire document.

Upvotes: 0

Views: 341

Answers (3)

Michael Kay
Michael Kay

Reputation: 163587

Is a search for a particular Id performed using an XPath expression such as:

 //Field[@Id=$vSearchId]

potentially expensive?

Yes, it is potentially expensive. But only potentially. With many processors, defining an xsl:key and using the key() function will speed this query up (by creating an index). But a processor like Saxon-EE with a smart optimizer will build the index automatically without you asking for it explicitly.

Upvotes: 1

Wolfgang Schindler
Wolfgang Schindler

Reputation: 28

You could define a key: <xsl:key name="id-register" match="Field" use="@Id"/>

Afterwards you could use this key to process occurrences of <Field> with a specific Id:

<xsl:for-each select="key('id-register','10')"> <!-- Do Stuff --> </xsl:for-each>

Upvotes: 1

michael.hor257k
michael.hor257k

Reputation: 117102

I looked at xsl:key but I wasn't sure how to use it for a search across the entire document.

Like this?

<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:key name="fld" match="Field" use="@Id" />
<xsl:variable name="vSearchId">6</xsl:variable>

<xsl:template match="/">
    <xsl:copy-of select="key('fld', $vSearchId)"/>
</xsl:template>

</xsl:stylesheet>

Upvotes: 2

Related Questions