Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing and parsing XML as a parameter to XSLT 2.0

Tags:

xslt

I'm trying to figure out how to pass XML into a XSLT document and parse it as you would on any node.

XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:param name="xmlparam"></xsl:param>

    <xsl:template match="/">
        <xsl:value-of select="node()"></xsl:value-of>
        <xsl:value-of select="$xmlparam/coll"></xsl:value-of>
    </xsl:template>
</xsl:stylesheet>

xmlparam:

<?xml version="1.0" encoding="UTF-8"?>

<coll>
    <title>Test</title>
    <text>Some text</text>
</coll>

Input:

<?xml version="1.0" encoding="UTF-8"?>

<coll>
    Root doc
</coll>

Output:

<?xml version="1.0" encoding="UTF-8"?>
    Root doc

XPTY0019: Required item type of first operand of '/' is node(); supplied value has item type xs:untypedAtomic

Does anyone know how to parse XML passed in as a parameter to XSLT? Due to certain restraints, I cannot read in a file, it needs to be a parameter.

like image 246
user489481 Avatar asked Nov 23 '22 18:11

user489481


1 Answers

You could get your XML input to be parsed by the style sheet by using the document function, e.g. like (from memory, so maybe not completely accurate)

<xsl:variable name="myData" select="document('myData')"/>

AND registering a custom URIResolver with the with your Transformer. This custom URIResolver will get "myData" as value of the parameter href of its resolve method and could then obtain the content of the document from e.g. a String. This would give you roughly the same flexibility as adding the content as a parameter.

Code sketch (assuming the obvious implementation of MyURIResolver):

Transformer myTransformer = getMyTransformer();
String myXmlDocument = getMyXmlDocumetAsString();
URIResolver myURIResolver = new MyURIResolver();
myURIResolver.put("myData", myXmlDocument);
myTransformer.setURIResolver(myURIResolver);
myTransformer.transform(source, result);
like image 142
Jan Avatar answered Dec 16 '22 11:12

Jan