是否有可用于Java(或PostgreSQL)的良好XML-to-Table?

我正在寻找类似的东西:XMLTABLE, http : //www.ibm.com/developerworks/data/library/techarticle/dm-0708nicola/

在PostgreSQL中是否存在类似的东西,或者哪个最接近?

或者另一种方式,是否有可以实现此目的的Java库?


编辑:

感谢Erwin(他的评论中的答案几乎正是我所寻找的)。

但是,也许我可以建议对此进行扩展。

考虑一下,我们有一个xml文档,如:

 this is the first comment this is the second comment  

虽然这是一个简单的例子,但也要考虑“comment”可能非常复杂。

我现在的问题是:使用XMLTable函数(或Erwin的实现),我们需要指定path_to_data即在这种情况下( /comment )。

但是,如果我希望我的返回模式类似于: [photo_id, comment_text]

无法从datanum的父元素中获取数据。

因此可以以某种方式修改您的代码来执行此操作吗? 我的猜测是有一些比xpath函数更复杂的东西,它本质上通过跟踪父代返回数据子集。

例如:

  this is the first comment   this is the second comment  

在这种情况下,我们可以访问“/comments/@photo_id”

我终于有时间仔细看看了。 从我在你的例子中收集的内容来看,这可能是你正在寻找的:

测试设置:

我添加了另一个节点以明确我的观点:

 -- DROP TABLE t; CREATE TEMP TABLE t (x xml); INSERT INTO t VALUES ( '  this is the first 123 comment this is the second 123 comment   this is the first 124 comment this is the second 124 comment this is the third 124 comment  '::xml); 

查询:

 SELECT (xpath('./@photo_id', c.node))[1] AS photo_id , unnest(xpath('./comment/text()', c.node)) AS descriptor FROM ( SELECT unnest(xpath('./comments', x)) AS node FROM t ) c; 

结果:

  photo_id | descriptor ----------+-------------------------------- 123 | this is the first 123 comment 123 | this is the second 123 comment 124 | this is the first 124 comment 124 | this is the second 124 comment 124 | this is the third 124 comment 

结果看起来非常简单,但这让我很头疼(不久前,实际上)。

关键因素是函数xpath()和unnest() 。 诀窍是分两步完成。 您可以在此相关答案中找到更多解释。

PostgreSQL确实支持XML数据类型,但没有直接支持XML到表的转换 。 您可以编写一个XSLT样式表来将XML转换为SQL INSERT语句,或者查看一个映射工具,例如Castor ,它可以在XML,Java bean和SQL之间进行转换。