【问题标题】:Get values from XML从 XML 中获取值
【发布时间】:2022-10-17 09:39:05
【问题描述】:

我有一个数据类型为XML 的表。我想通过读取那个 XML 列来获取数据。

这是存储在该列中的 XML:

<BizMsg xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:asx:xsd:xasx.802.001.04 ASX_AU_CHS_comm_802_001_04_xasx_802_001_04.xsd">
  <Document xmlns="urn:iso:std:iso:20022:tech:xsd:sese.023.001.07">
    <SctiesSttlmTxInstr>
      <TxId>
        01114|0045852600
      </TxId>
    </SctiesSttlmTxInstr>
  </Document>
</BizMsg>

我想在&lt;TxId&gt; 标签中获取价值。

我尝试运行此查询,但没有得到任何结果:

DECLARE @myDoc XML  
SET @myDoc = ( Select data from TableName Where Id = 56 )   // which returns XML column value from table
  
SELECT  @myDoc.value('(/BizMsg/Document/SctiesSttlmTxInstr/TxId)[1]', 'nvarchar(max)' )   

请指教 - 我做错了什么?

【问题讨论】:

  • Where Id = 56 ...你没有Id
  • " Select data from TableName Where Id = 56 " 此查询返回存储在表中的 XML 列
  • SQL是一些触发器/事务吗?
  • 不,那里没有

标签: sql-server xml


【解决方案1】:

你是忽略定义的XML 命名空间在您的文档中 - 这就是您没有得到任何结果的原因....

<BizMsg xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
        xmlns="urn:asx:xsd:xasx.802.001.04 ASX_AU_CHS_comm_802_001_04_xasx_802_001_04.xsd">
        **** this is the root level XML namespace
    <Document xmlns="urn:iso:std:iso:20022:tech:xsd:sese.023.001.07">
              **** this is the XML namespace for <Document> and its children

尝试这个:

WITH XMLNAMESPACES ('urn:asx:xsd:xasx.802.001.04 ASX_AU_CHS_comm_802_001_04_xasx_802_001_04.xsd' AS RootNS,
                    'urn:iso:std:iso:20022:tech:xsd:sese.023.001.07' AS DocNS)
SELECT
    TxId = XC.value('(DocNS:SctiesSttlmTxInstr/DocNS:TxId/text())[1]', 'varchar(100)')
FROM
    YourTableNameHere
CROSS APPLY
    XmlDoc.nodes('/RootNS:BizMsg/DocNS:Document') AS XT(XC)

根据您的输入,我得到以下结果:

TxId
----------------
01114|0045852600       

【讨论】:

  • 我需要在某处声明 XmlDoc 吗?
  • 您需要将“YourTableNameHere”替换为您的表名和“XmlDoc”您的该表中 XML 列的列名
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 2017-08-15
  • 2016-11-05
  • 2018-10-27
  • 2012-07-24
相关资源
最近更新 更多