0

I need help to parse XML in SQL Server. I need to get "d1p1:Val2" value and concatenation of values for "d2p1:string".

<FirstData xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:d1p1="http://XXXXXX" xmlns="http://YYYYYY" i:type="d1p1:StaticInfo">
<Timestamp>0</Timestamp>
<ActionResult i:nil="true" />
<d1p1:Val1 xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>1</d2p1:string>
<d2p1:string>2</d2p1:string>
<d2p1:string>3</d2p1:string>
<d2p1:string>4</d2p1:string>
</d1p1:Val1>
<d1p1:Val2>false</d1p1:Val2>
</FirstData>
Bohdan
  • 3
  • 2

2 Answers2

0

Try something like this (can't test it myself ) :

SELECT Instructions.query('
     declare namespace d1p1="http://XXXXXX";
     declare namespace d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays";
        concat(//d1p1:Val2, " ", //d2p1:string[1]);
    ')

I think you just have to elaborate a bit on this

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

Your question is not very clear, but this might help you:

DECLARE @xml XML=
N'<FirstData xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d1p1="http://XXXXXX" xmlns="http://YYYYYY" i:type="d1p1:StaticInfo">
  <Timestamp>0</Timestamp>
  <ActionResult i:nil="true" />
  <d1p1:Val1 xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <d2p1:string>1</d2p1:string>
    <d2p1:string>2</d2p1:string>
    <d2p1:string>3</d2p1:string>
    <d2p1:string>4</d2p1:string>
  </d1p1:Val1>
  <d1p1:Val2>false</d1p1:Val2>
</FirstData>';

WITH XMLNAMESPACES(DEFAULT 'http://YYYYYY'
                          ,'http://XXXXXX' AS d1p1
                          ,'http://schemas.microsoft.com/2003/10/Serialization/Arrays' AS d2p1)
SELECT @xml.value(N'(/FirstData/d1p1:Val2/text())[1]','bit') AS D1P1_Val2
      ,@xml.query(N'data(/FirstData/d1p1:Val1/d2p1:string/text())').value(N'text()[1]',N'nvarchar(max)') AS AllStrings;

The result

D1P1_Val2   AllStrings
0           1 2 3 4

This is the - not recommended - minimal query:

SELECT @xml.value(N'(//*:Val2)[1]','bit') AS D1P1_Val2
      ,@xml.query(N'data(//*:string)').value(N'.',N'nvarchar(max)') AS AllStrings;
Shnugo
  • 66,100
  • 9
  • 53
  • 114