1

I trying parse xml from file. But result is empty

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?

2 Answers 2

2

You could use 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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.