简体   繁体   English

在SQL Server表中解析XML

[英]Parse XML in SQL Server table

I trying parse xml from file. 我尝试从文件解析xml。 But result is empty 但结果是空的

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>

How to parse in table? 如何在表中解析?

Color    color_code
BLACK      1234
RED        1234

I tried this query: 我试过这个查询:

 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)

First column is correct. 第一列是正确的。 But second is not. 但其次不是。 How to fix? 怎么修?

You could use query : 你可以使用query

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);

db<>fiddle demo db <>小提琴演示

You should try : 你应该试试 :

 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);

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

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