XML Parsing

Bobby P 231 Reputation points
2021-07-27T15:00:01.62+00:00

I have XML Data that may or may not have <Section> text...

If the <Section> has text like so...

<Section>Blah Blah Blah Section Text</Section>

then I want to concatenate that <Section> Text Block with the <Section><Content> text

If the <Section> has no text, like so...

<Section>

Then I just want the <Section><Content> text block

Is there an easy way to do this?

Thanks for your review and am hopeful for a response.

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,637 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bobby P 231 Reputation points
    2021-07-27T20:08:30.547+00:00

    I think this is working...

                        CASE
                            WHEN [n].[value] ('(./Section/text())[1]', 'VARCHAR(MAX)') <> ' '
                                THEN CONCAT (
                                                'WARNING: ',
                                                [n].[value] ('(./Section/text())[1]', 'VARCHAR(MAX)'),
                                                ' ',
                                                'COMMON USES: ',
                                                [n].[value] ('(./Section//Content/text())[1]', 'VARCHAR(MAX)')
                                            )
                            ELSE CONCAT (
                                            'COMMON USES: ',
                                            [n].[value] ('(./Section//Content/text())[1]', 'VARCHAR(MAX)')
                                        )
                        END         AS [Txt]
    
    0 comments No comments

  2. Yitzhak Khabinsky 25,856 Reputation points
    2021-07-27T21:41:57.573+00:00

    Hi @Bobby P ,

    Here is how to do much simpler.

    SQL

    DECLARE @xml XML =  
    N'<root>  
    	<r>  
    		<Section>Section text<Content>Content Text</Content></Section>  
    	</r>  
    	<r>  
    		<Section>  
    			<Content>2nd Content Text</Content>  
    		</Section>  
    	</r>  
    </root>';  
      
    SELECT CONCAT('WARNING: ' + c.value('(Section/text())[1]', 'VARCHAR(30)') + SPACE(1)  
    	, 'COMMON USES: ', c.value('(Section/Content/text())[1]', 'VARCHAR(30)')) AS result  
    FROM @xml.nodes('/root/r') AS t(c);  
    

    Output

    +-------------------------------------------------+  
    |                     result                      |  
    +-------------------------------------------------+  
    | WARNING: Section text COMMON USES: Content Text |  
    | COMMON USES: 2nd Content Text                   |  
    +-------------------------------------------------+  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.