首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析SQL Server表中的XML

解析SQL Server表中的XML
EN

Stack Overflow用户
提问于 2018-10-28 00:38:56
回答 2查看 109关注 0票数 1

我尝试从文件中解析xml。但是结果是空的

XML:

代码语言:javascript
复制
<custom-attributes>
    <custom-attribute attribute-id="color" xml:lang="x-default">BLACK</custom-attribute>
    <custom-attribute attribute-id="color_code" xml:lang="x default">1234</custom-attribute>
</custom-attributes>

<custom-attributes>
    <custom-attribute attribute-id="color_style" xml:lang="x-default">free</custom-attribute>
    <custom-attribute attribute-id="color" xml:lang="x-default">RED</custom-attribute>
    <custom-attribute attribute-id="color_code" xml:lang="x default">1234</custom-attribute>
</custom-attributes>

如何在表中解析?

代码语言:javascript
复制
Color    color_code
BLACK      1234
RED        1234

我尝试了这个查询:

代码语言:javascript
复制
 DECLARE @xml XML = '
<custom-attributes>
            <custom-attribute attribute-id="color" xml:lang="x-default">BLACK</custom-attribute>
            <custom-attribute attribute-id="color_code" xml:lang="x default">1234</custom-attribute>
</custom-attributes>

<custom-attributes>
            <custom-attribute attribute-id="color_style" xml:lang="x-default">free</custom-attribute>
            <custom-attribute attribute-id="color" xml:lang="x-default">RED</custom-attribute>
            <custom-attribute attribute-id="color_code" xml:lang="x default">1234</custom-attribute>
</custom-attributes>'

SELECT 
    Color =   x.t.value('(./custom-attribute)[1]', 'varchar(200)')
FROM
    @xml.nodes('/custom-attributes') AS x(t)

第一列是正确的。但第二个不是。如何修复?

EN

回答 2

Stack Overflow用户

发布于 2018-10-28 01:02:29

您可以使用query

代码语言:javascript
复制
SELECT 
  Color=x.t.query('(./custom-attribute[@attribute-id="color"]/text())')
 ,Color_code=x.t.query('(./custom-attribute[@attribute-id="color_code"]/text())')
FROM @xml.nodes('/custom-attributes') AS x(t);
票数 2
EN

Stack Overflow用户

发布于 2018-10-28 01:05:50

您应该尝试:

代码语言:javascript
复制
 Declare @fileData  XML 
             Select @fileData=BulkColumn from OpenRowSet(Bulk'PATH\FILENAME.xml',Single_blob) x;
             select 
                x.xData.value('custom-attribute[@attribute-id="color"][1]','nvarchar(max)') as color,
                x.xData.value('custom-attribute[@attribute-id="color_code"][1]','nvarchar(max)') as color_code,
                x.xData.value('custom-attribute[@attribute-id="color_style"][1]','nvarchar(max)')as color_style
             from @fileData.nodes('/custom-attributes') 
             x(xData);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53024111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档