简体   繁体   English

TSQL未能解析XML(命名空间)

[英]TSQL-failing to parse XML(namespaces)

Here is a my SQL: 这是我的SQL:

    create table sqm (data xml)    
    insert into sqm
    select '<DataSet xmlns="http://www.bnr.ro/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bnr.ro/xsd nbrfxrates.xsd">
            <Cube date="2017-06-30">
                <Rate currency="AED">1.0867</Rate>
                <Rate currency="AUD">3.0665</Rate>
                <Rate currency="BGN">2.3284</Rate>
            </Cube>
            </DataSet>'

    select
    m.c.value('@date', 'date') as valuta
    from sqm as s
    outer apply s.data.nodes('/DataSet/Body/Cube') as m(c)

After spending hours trying to find out why my SQL kept returning NULL in the db, I discovered that my problem was due to Hyperlink references at the very beginning of the XML(after DataSet). 在花了几个小时试图找出为什么我的SQL为什么在数据库中不断返回NULL之后,我发现我的问题是由于XML开头(在DataSet之后)的超链接引用引起的。 I really want to know why is this happening and who can I delete everything between <DataSet end > . 我真的很想知道为什么会这样,并且谁可以删除<DataSet end >之间的所有内容。 Is there any other option? 还有其他选择吗?

if you can think of a better title, please edit. 如果您认为标题更好,请进行编辑。

You need to declare the namespace using WITH XMLNAMESPACES 您需要使用WITH XMLNAMESPACES声明名称空间

Also your example XML has no Body element so I removed that from the Xpath. 另外,您的示例XML没有Body元素,因此我从Xpath中删除了它。

Demo 演示

WITH XMLNAMESPACES (DEFAULT 'http://www.bnr.ro/xsd')  

select
m.c.value('@date', 'date') as valuta
from sqm as s
outer apply s.data.nodes('/DataSet/Cube') as m(c)

Or alternatively you can use 或者您可以使用

select
m.c.value('@date', 'date') as valuta
from sqm as s
outer apply s.data.nodes('/*:DataSet/*:Cube') as m(c)

Apart of Martin's solutions(+1), there is one more solution that is using inline declaration of XML namespaces thus: 除了Martin的解决方案(+1)之外,还有一种解决方案使用XML名称空间的内联声明,因此:

-- Solution #1
select  m.c.value('@date', 'date') as valuta
from    sqm as s
outer apply s.data.nodes('declare default element namespace "http://www.bnr.ro/xsd";DataSet/Cube') as m(c)

-- Solution #2
select  m.c.value('@date', 'date') as valuta
from    sqm as s
outer apply s.data.nodes('
    declare default element namespace "http://www.bnr.ro/xsd";  
    declare namespace xsi="http://www.w3.org/2001/XMLSchema-instance";  
    declare namespace schemaLocation="http://www.bnr.ro/xsd nbrfxrates.xsd";  
    DataSet/Cube') as m(c) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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