简体   繁体   中英

How to extract data from xml like string in SQL Server

Consider below XBRL string (xbrl is an xml derived language for financial reporting)

<xbrl>
  <ifrs-full:cash contextRef="2017" unitRef="USD">1000</ifrs-full:cash>
  <ifrs-full:investment contextRef="2017" unitRef="USD">500</ifrs-full:investment>
  <ifrs-full:inventory contextRef="2017" unitRef="USD">800</ifrs-full:inventory>
</xbrl>

How can I extract this information in SQL Server and get something like this:

Element             |ContextRef|UnitRef|Value
--------------------+----------+-------+-------
ifrs-full:cash      |2017      |USD    |1000
ifrs-ful:investment |2017      |USD    | 500
ifrs-ful:investment |2017      |USD    | 800

You first need to fix the invalid XML (done below with a replace). Then you can use Xpath functions on it.

DECLARE @xbrlString VARCHAR(MAX) = '<xbrl>
      <ifrs-full:cash contextRef="2017" unitRef="USD">1000</ifrs-full:cash>
      <ifrs-full:investment contextRef="2017" unitRef="USD">500</ifrs-full:investment>
      <ifrs-full:inventory contextRef="2017" unitRef="USD">800</ifrs-full:inventory>
    </xbrl>';

DECLARE @xbrlXml XMl = REPLACE(@xbrlString, 
                               '<xbrl>', 
                               '<xbrl xmlns:ifrs-full="http://dummy">');

SELECT Element = 'ifrs-full:' + n.n.value('local-name(.)', 'SYSNAME'),
       contextRef = n.n.value('@contextRef', 'INT'),
       UnitRef = n.n.value('@unitRef', 'CHAR(3)'),
       Value = n.n.value('text()[1]', 'INT')
FROM   @xbrlXml.nodes('xbrl/*[namespace-uri() = "http://dummy"]') AS n(n); 

returns

+----------------------+------------+---------+-------+
|       Element        | contextRef | UnitRef | Value |
+----------------------+------------+---------+-------+
| ifrs-full:cash       |       2017 | USD     |  1000 |
| ifrs-full:investment |       2017 | USD     |   500 |
| ifrs-full:inventory  |       2017 | USD     |   800 |
+----------------------+------------+---------+-------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM