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>
1

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

is it possible to add a delimiter when concatenating?
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

3 Comments

An error: "XQuery [query()]: No more tokens expected at the end of the XQuery expression. Found ';'."
I never said it's a full solution, just a start
As the error message says, the final ";" in the query should be removed.

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.