Spongebob Comrade
Spongebob Comrade

Reputation: 1568

XSL query inner xml

Say this is my xml :

<History>
    <University>TSU</University>
    <Payload>
        <Attrib Order="0">OVERSEA</Attrib>
        <Attrib Order="1">GRADE2</Attrib>
        <Attrib Order="2">&lt;Person&gt;&lt;ID&gt;TQR344&lt;/ID&gt;&lt;/Person&gt;</Attrib>
        <Attrib Order="3">3566644</Attrib>
    </Payload>
</History>

And I want to query the inner XML inside Order=2 tag and read ID of the person.

I have created this so far :

<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     >

    <xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="no" />

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

    <xsl:template name="Person" match="//History">
        <Event>
            <Uni><xsl:value-of select="University" /></Uni>
            <ID><xsl:value-of select="Payload/Attrib[@Order='2']/Person/ID"  disable-output-escaping="yes" /></ID>
        </Event>
    </xsl:template>
</xsl:stylesheet>

But as you can see it is not working.

Also I assigned the inner XML into a variable and tried to query that variable and It didn't work too.

Is it possible to do that via xsl ?

Limitations : I cannot change xml format. But maybe I was able to move from xsl ver 1 to new versions.

Upvotes: 0

Views: 340

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117140

I want to query the inner XML inside Order=2 tag

The tag in question does not contain any XML; its content is a string and needs to be manipulated using string functions. Try:

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:template match="/History">
    <Event>
        <Uni>
            <xsl:value-of select="University" />
        </Uni>
        <ID>
            <xsl:value-of select="substring-before(substring-after(Payload/Attrib[@Order='2'], '&lt;ID&gt;'),'&lt;/ID&gt;&lt;')"/>
        </ID>
    </Event>
</xsl:template>

</xsl:stylesheet>

Note:

1. This:

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

creates an infinite loop and will crash your processor.

2. Alternatively, you could serialize the string back into XML and process the result as XML; in XSLT 1.0, this can be done only by outputting the string with the escaping disabled, saving the result as a new document, then processing the new document with another XSLT stylesheet. Using XSLT 3.0 (or a processor that supports serializing as an extension) this can be all done during the same transformation.

Upvotes: 1

Related Questions