XSLT 作为构建器/工厂
有没有某种方法可以滥用 XSLT 作为对象的构建器/工厂而不是生成文本输出?单独的 XPath-epressions 对于查询简单的东西来说非常有用,但是在我在 XSLT 中使用递归的情况下会变得乏味。
换句话说,我想使用 XSLT 的模板匹配语义,但每个模板将构造并返回一个对象而不是节点或文本。
该用例将实现一个模型转换器,其中目标模型不是一些 XML 内容,而是自定义域模型(作为内存中的对象图)。
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 would 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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有趣的问题,你所问的有点像像 Alntlr 这样的解析器生成器生成的代码。
我认为您想要的通过创建对象作为 XSLT 转换的副作用是可能的。您可以使用如下代码从 XSLT 脚本创建对象并调用对象的方法:
在 XSLT 脚本中实例化 Java 对象;
稍后在脚本中使用它创建对象树:
这将调用 my.sample.Factory 类上的静态 getInstance() 方法创建的工厂对象上的 getInstance(String, String) 方法。工厂还必须保留创建的对象,以便在转换完成后,您可以从工厂实例中检索由转换实例化的对象树。您可以预先创建工厂并将其作为参数传递给脚本,而不是在脚本中创建工厂。
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;
Using it to create the object tree later on in the script:
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.
我的本能是让 XSLT 转换以通常的方式生成一个 XML 树,然后将该树通过管道传输到 Java 数据绑定工具中,将其转换为 Java 对象。 (当然,树永远不需要序列化为词法 XML;您可以使用 SAX 调用连接组件。)。
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.).