开发者

XSLT as builder/factory

开发者 https://www.devze.com 2023-03-16 02:15 出处:网络
Is there some way to abuse XSLT as a builder/factory for objects instead of generating textual output? XPath-epressions alone are great for querying simple stuff, but get tedious in circumstances wher

Is there some way to abuse XSLT as a builder/factory for objects instead of generating textual output? XPath-epressions alone are great for querying simple stuff, but get tedious in circumstances where I would use recursion in XSLT.

In other words, I'd like to use the template-matching semantics of XSLT, but each template would construct and return an object instead of a node or text.

The use case 开发者_如何学Gowould be implementing a model transformator where the target model is not some XML stuff, but a custom domain model (as an object graph in memory).


Interesting question, what you are asking is somewhat like the code generated by a parser generator like Alntlr would create.

I think what you want is possible, by creating the objects as a side effect of the XSLT transform. You can create objects and call methods on objects from an XSLT script using code like this:

Instantiate a Java object in your XSLT script;

<!-- Create object factory. -->
<xsl:variable name="factory" xmlns:java="http://xml.apache.org/xalan/java"
    select="java:my.sample.Factory.getInstance()" />

Using it to create the object tree later on in the script:

<xsl:template match="node">
    <xsl:variable name="myObject" xmlns:java="http://xml.apache.org/xalan/java"
                select="java:getInstance($provider, string(@parent), string(@type))" />

This would call the method getInstance(String, String) on the factory object created by the static getInstance() method on your my.sample.Factory class. The factory would also have to keep the objects created so that after the transform finishes you can retrieve the object tree instantiated by the transform from the factory instance. Instead of create the factory in the script you can create it beforehand and pass it to the script as a parameter.


My instinct would be to have your XSLT transformation generate an XML tree in the usual way, and then pipe this tree into a Java data binding tool to turn it into Java objects. (The tree, of course, never needs to be serialized as lexical XML; you can probably connect the components using SAX calls.).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号