是否有一个好的 XML-to-Table 可以在 Java(或 PostgreSQL)中使用?

2024-02-18

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

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

或者换一种方式,有没有一个Java库可以完成这个任务?


EDIT:

感谢埃尔文(他评论中的答案几乎正是我正在寻找的)。

然而,也许我可以建议对此进行扩展。

考虑一下,我们有一个 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”.


我终于有时间仔细观察了。根据我在您的示例中收集的信息,这可能就是您正在寻找的内容:

测试设置:

我添加了另一个节点来阐明我的观点:

-- 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);

Query:

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;

Result:

 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() http://www.postgresql.org/docs/current/interactive/functions-xml.html#FUNCTIONS-XML-PROCESSING and unnest() http://www.postgresql.org/docs/current/interactive/functions-array.html#ARRAY-FUNCTIONS-TABLE。诀窍是分两步完成。您可以在以下位置找到更多解释这个相关答案 https://stackoverflow.com/a/8274679/939860.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否有一个好的 XML-to-Table 可以在 Java(或 PostgreSQL)中使用? 的相关文章

随机推荐