如何读取使用 Node.js 查询的 Oracle 数据库 XML 列?

问题描述

我需要读取将我的查询带到 Oracle 中的数据库的值,我使用 oracle DB 和 node.js。 oracle DB 在具有 XML 的列中返回这些值,但具有正常值的其他列返回正常。

{
  "tramaenv": {
    "_readableState": {
      "objectMode": false,"highWaterMark": 16384,"buffer": {
        "head": null,"tail": null,"length": 0
      },"length": 0,"pipes": null,"pipesCount": 0,"flowing": null,"ended": false,"endEmitted": false,"reading": false,"sync": true,"needReadable": false,"emittedReadable": false,"readableListening": false,"resumeScheduled": false,"emitClose": true,"autoDestroy": false,"destroyed": false,"defaultEncoding": "utf8","awaitDrain": 0,"readingMore": false,"decoder": null,"encoding": null
    },"readable": true,"_events": {},"_eventsCount": 1,"_writableState": {
      "corkedRequestsFree": {
        "next": null,"entry": null
      }
    },"writable": true,"allowHalfOpen": true,"offset": 1
  }
}

但真正的内容是这个 XML

<soapenv:Envelope >
    <soapenv:Header/>
    <soapenv:Body>
        <imp:obtNroConstanciaElectronica>
            <reqObtNroConstanciaElectronica>
                <idecotizacion>12668264</idecotizacion>
                <ideprod>2003</ideprod>
            </reqObtNroConstanciaElectronica>
        </imp:obtNroConstanciaElectronica>
    </soapenv:Body>
</soapenv:Envelope>

解决方法

如果您的样本数据是:

CREATE TABLE table_name ( id,xml ) AS
SELECT 1,'<soapenv:Envelope xmlns:soapenv="https://example.com/soapenv" xmlns:imp="https://example.com/imp">
    <soapenv:Header/>
    <soapenv:Body>
        <imp:obtNroConstanciaElectronica>
            <reqObtNroConstanciaElectronica>
                <idecotizacion>12668264</idecotizacion>
                <ideprod>2003</ideprod>
            </reqObtNroConstanciaElectronica>
        </imp:obtNroConstanciaElectronica>
    </soapenv:Body>
</soapenv:Envelope>' FROM DUAL;

(注意:soapenvimp 的命名空间是在 XML 中声明的。)

然后就可以使用SQL查询了:

SELECT id,x.*
FROM   table_name t
       CROSS APPLY XMLTABLE(
         XMLNAMESPACES(
           'https://example.com/soapenv' AS "soapenv",'https://example.com/imp' AS "imp"
         ),'/soapenv:Envelope/soapenv:Body/imp:obtNroConstanciaElectronica/reqObtNroConstanciaElectronica'
         PASSING XMLTYPE( t.xml )
         COLUMNS
           idecotizacion NUMBER PATH './idecotizacion',ideprod NUMBER PATH './ideprod'
       ) x

输出为:

ID IDECOTIZACION IDEPROD
1 12668264 2003

然后,您只需像在 node.js 脚本中调用任何其他 SQL 查询一样调用该查询并获取值。

,

node-oracledb 文档有一个 whole section on XMLType

看来您已成功提取为 CLOB(这是避免 XML 长度被限制为最大 VARCHAR2 长度所必需的),即。你做过类似的事情:

const sql = `SELECT XMLTYPE.GETCLOBVAL(res) FROM resource_view`;

您可以stream the LOB,或者告诉node-oracledb 到return it directly as a string。要执行后者,请将其添加到脚本的顶部:

oracledb.fetchAsString = [ oracledb.CLOB ];

您应该对两种解决方案进行基准测试并使用最好的。