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

时间:2012-02-19 13:43:47

标签: java postgresql xml-parsing

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

PostgreSQL中是否存在类似的内容,或者最接近的内容是什么?

或者换句话说,是否有可以实现此目的的Java库?


修改

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

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

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

<comments photo_id=“123”>
    </comment>this is the first comment</comment>
    </comment>this is the second comment</comment>
</comments>

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

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

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

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

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

例如:

<comments photo_id=“123”>
    </comment>this is the first comment</comment>
</comments>

<comments photo_id=“123”>
    </comment>this is the second comment</comment>
</comments>

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

2 个答案:

答案 0 :(得分:2)

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

测试设置:

我添加了另一个节点以明确指出:

-- DROP TABLE t;
CREATE TEMP TABLE t (x xml);
INSERT INTO t VALUES (
'<tbl>
<comments photo_id="123">
     <comment>this is the first 123 comment</comment>
     <comment>this is the second 123 comment</comment>
</comments>
<comments photo_id="124">
     <comment>this is the first 124 comment</comment>
     <comment>this is the second 124 comment</comment>
     <comment>this is the third 124 comment</comment>
</comments>
</tbl>'::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()。诀窍是分两步完成。您可以在this related answer找到更多解释。

答案 1 :(得分:0)

PostgreSQL确实支持XML数据类型,但是no direct support for XML-to-table conversion。您可以编写一个XSLT样式表来将XML转换为SQL INSERT语句,或者查看一个映射工具,例如Castor,它可以在XML,Java bean和SQL之间进行转换。

相关问题