Concatenate all values of the same XML element using XPath/XQuery





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







14















I have an XML value like this:



<R>
<I>A</I>
<I>B</I>
<I>C</I>
...
</R>


I want to concatenate all I values and return them as a single string: ABC....



Now I know that I can shred the XML, aggregate the results back as a nodeless XML, and apply .values('text()[1]', ...) to the result:



SELECT
(
SELECT
n.n.value('text()[1]', 'varchar(50)') AS [text()]
FROM
@MyXml.nodes('/R/I') AS n (n)
FOR XML
PATH (''),
TYPE
).value('text()[1]', 'varchar(50)')
;


However, I would like to do all that using XPath/XQuery methods only, something like this:



SELECT @MyXml. ? ( ? );


Is there such a way?



The reason I am looking for a solution in this direction is because my actual XML contains other elements too, for instance:



<R>
<I>A</I>
<I>B</I>
<I>C</I>
...
<J>X</J>
<J>Y</J>
<J>Z</J>
...
</R>


And I would like to be able to extract both the I values as a single string and the J values as a single string without having to use an unwieldy script for each.










share|improve this question





























    14















    I have an XML value like this:



    <R>
    <I>A</I>
    <I>B</I>
    <I>C</I>
    ...
    </R>


    I want to concatenate all I values and return them as a single string: ABC....



    Now I know that I can shred the XML, aggregate the results back as a nodeless XML, and apply .values('text()[1]', ...) to the result:



    SELECT
    (
    SELECT
    n.n.value('text()[1]', 'varchar(50)') AS [text()]
    FROM
    @MyXml.nodes('/R/I') AS n (n)
    FOR XML
    PATH (''),
    TYPE
    ).value('text()[1]', 'varchar(50)')
    ;


    However, I would like to do all that using XPath/XQuery methods only, something like this:



    SELECT @MyXml. ? ( ? );


    Is there such a way?



    The reason I am looking for a solution in this direction is because my actual XML contains other elements too, for instance:



    <R>
    <I>A</I>
    <I>B</I>
    <I>C</I>
    ...
    <J>X</J>
    <J>Y</J>
    <J>Z</J>
    ...
    </R>


    And I would like to be able to extract both the I values as a single string and the J values as a single string without having to use an unwieldy script for each.










    share|improve this question

























      14












      14








      14


      4






      I have an XML value like this:



      <R>
      <I>A</I>
      <I>B</I>
      <I>C</I>
      ...
      </R>


      I want to concatenate all I values and return them as a single string: ABC....



      Now I know that I can shred the XML, aggregate the results back as a nodeless XML, and apply .values('text()[1]', ...) to the result:



      SELECT
      (
      SELECT
      n.n.value('text()[1]', 'varchar(50)') AS [text()]
      FROM
      @MyXml.nodes('/R/I') AS n (n)
      FOR XML
      PATH (''),
      TYPE
      ).value('text()[1]', 'varchar(50)')
      ;


      However, I would like to do all that using XPath/XQuery methods only, something like this:



      SELECT @MyXml. ? ( ? );


      Is there such a way?



      The reason I am looking for a solution in this direction is because my actual XML contains other elements too, for instance:



      <R>
      <I>A</I>
      <I>B</I>
      <I>C</I>
      ...
      <J>X</J>
      <J>Y</J>
      <J>Z</J>
      ...
      </R>


      And I would like to be able to extract both the I values as a single string and the J values as a single string without having to use an unwieldy script for each.










      share|improve this question














      I have an XML value like this:



      <R>
      <I>A</I>
      <I>B</I>
      <I>C</I>
      ...
      </R>


      I want to concatenate all I values and return them as a single string: ABC....



      Now I know that I can shred the XML, aggregate the results back as a nodeless XML, and apply .values('text()[1]', ...) to the result:



      SELECT
      (
      SELECT
      n.n.value('text()[1]', 'varchar(50)') AS [text()]
      FROM
      @MyXml.nodes('/R/I') AS n (n)
      FOR XML
      PATH (''),
      TYPE
      ).value('text()[1]', 'varchar(50)')
      ;


      However, I would like to do all that using XPath/XQuery methods only, something like this:



      SELECT @MyXml. ? ( ? );


      Is there such a way?



      The reason I am looking for a solution in this direction is because my actual XML contains other elements too, for instance:



      <R>
      <I>A</I>
      <I>B</I>
      <I>C</I>
      ...
      <J>X</J>
      <J>Y</J>
      <J>Z</J>
      ...
      </R>


      And I would like to be able to extract both the I values as a single string and the J values as a single string without having to use an unwieldy script for each.







      sql-server sql-server-2014 xml xquery






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked May 6 at 11:04









      Andriy MAndriy M

      16.6k63777




      16.6k63777






















          3 Answers
          3






          active

          oldest

          votes


















          11














          This might work for you:



          select @MyXml.value('/R[1]', 'varchar(50)')


          It picks up all text() elements from the first R and below.



          If you just want all text() you can do



          select @MyXml.value('.', 'varchar(50)')


          If you want the values for I and J separate do this instead.



          select @MyXml.query('/R/I/text()').value('.', 'varchar(50)'),
          @MyXml.query('/R/J/text()').value('.', 'varchar(50)')





          share|improve this answer


























          • The last one was suggested to me in chat but I find the first one extremely helpful too. I might be able to generate the XML data differently so that I can apply the first method to it.

            – Andriy M
            May 6 at 12:10



















          7














          Depending on your actual XML structure you could consider using a loop like this:



          DECLARE @xml XML

          SELECT @xml = '<R>
          <I>A</I>
          <I>B</I>
          <I>C</I>
          <J>X</J>
          <J>Y</J>
          <J>Z</J>
          </R>'

          SELECT
          Tbl.Col.query('for $i in I return $i').value('.', 'nvarchar(max)'),
          Tbl.Col.query('for $i in J return $i').value('.', 'nvarchar(max)')
          FROM @xml.nodes('R') Tbl(Col);


          which outputs this:



          (No column name) | (No column name) 
          --------------- | ---------------
          ABC | XYZ


          See this fiddle






          share|improve this answer



















          • 1





            This is really good. I can easily adapt it to include delimiters whenever I need to. And it's not too verbose to be used as it is in case I want to extract strings both with and without delimiters in a uniform way.

            – Andriy M
            May 6 at 12:34



















          0














          If your elements and values really are short and distinct this works:



          declare @s varchar(99) = '<R><I>A</I><I>B</I><I>C</I></R>';

          select
          @s,
          REPLACE(TRANSLATE ( @s, '<>I/R', ' '), ' ', '');


          For non-trivial XML it may struggle, though.






          share|improve this answer
























          • The elements can be short, but the values in general are not, and I can't be sure they won't contain same characters as the element names do. Appreciate the outside the box approach, though.

            – Andriy M
            May 7 at 8:28












          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "182"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f237475%2fconcatenate-all-values-of-the-same-xml-element-using-xpath-xquery%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          3 Answers
          3






          active

          oldest

          votes








          3 Answers
          3






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          11














          This might work for you:



          select @MyXml.value('/R[1]', 'varchar(50)')


          It picks up all text() elements from the first R and below.



          If you just want all text() you can do



          select @MyXml.value('.', 'varchar(50)')


          If you want the values for I and J separate do this instead.



          select @MyXml.query('/R/I/text()').value('.', 'varchar(50)'),
          @MyXml.query('/R/J/text()').value('.', 'varchar(50)')





          share|improve this answer


























          • The last one was suggested to me in chat but I find the first one extremely helpful too. I might be able to generate the XML data differently so that I can apply the first method to it.

            – Andriy M
            May 6 at 12:10
















          11














          This might work for you:



          select @MyXml.value('/R[1]', 'varchar(50)')


          It picks up all text() elements from the first R and below.



          If you just want all text() you can do



          select @MyXml.value('.', 'varchar(50)')


          If you want the values for I and J separate do this instead.



          select @MyXml.query('/R/I/text()').value('.', 'varchar(50)'),
          @MyXml.query('/R/J/text()').value('.', 'varchar(50)')





          share|improve this answer


























          • The last one was suggested to me in chat but I find the first one extremely helpful too. I might be able to generate the XML data differently so that I can apply the first method to it.

            – Andriy M
            May 6 at 12:10














          11












          11








          11







          This might work for you:



          select @MyXml.value('/R[1]', 'varchar(50)')


          It picks up all text() elements from the first R and below.



          If you just want all text() you can do



          select @MyXml.value('.', 'varchar(50)')


          If you want the values for I and J separate do this instead.



          select @MyXml.query('/R/I/text()').value('.', 'varchar(50)'),
          @MyXml.query('/R/J/text()').value('.', 'varchar(50)')





          share|improve this answer















          This might work for you:



          select @MyXml.value('/R[1]', 'varchar(50)')


          It picks up all text() elements from the first R and below.



          If you just want all text() you can do



          select @MyXml.value('.', 'varchar(50)')


          If you want the values for I and J separate do this instead.



          select @MyXml.query('/R/I/text()').value('.', 'varchar(50)'),
          @MyXml.query('/R/J/text()').value('.', 'varchar(50)')






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 6 at 13:40

























          answered May 6 at 11:29









          Mikael ErikssonMikael Eriksson

          18.4k34689




          18.4k34689













          • The last one was suggested to me in chat but I find the first one extremely helpful too. I might be able to generate the XML data differently so that I can apply the first method to it.

            – Andriy M
            May 6 at 12:10



















          • The last one was suggested to me in chat but I find the first one extremely helpful too. I might be able to generate the XML data differently so that I can apply the first method to it.

            – Andriy M
            May 6 at 12:10

















          The last one was suggested to me in chat but I find the first one extremely helpful too. I might be able to generate the XML data differently so that I can apply the first method to it.

          – Andriy M
          May 6 at 12:10





          The last one was suggested to me in chat but I find the first one extremely helpful too. I might be able to generate the XML data differently so that I can apply the first method to it.

          – Andriy M
          May 6 at 12:10













          7














          Depending on your actual XML structure you could consider using a loop like this:



          DECLARE @xml XML

          SELECT @xml = '<R>
          <I>A</I>
          <I>B</I>
          <I>C</I>
          <J>X</J>
          <J>Y</J>
          <J>Z</J>
          </R>'

          SELECT
          Tbl.Col.query('for $i in I return $i').value('.', 'nvarchar(max)'),
          Tbl.Col.query('for $i in J return $i').value('.', 'nvarchar(max)')
          FROM @xml.nodes('R') Tbl(Col);


          which outputs this:



          (No column name) | (No column name) 
          --------------- | ---------------
          ABC | XYZ


          See this fiddle






          share|improve this answer



















          • 1





            This is really good. I can easily adapt it to include delimiters whenever I need to. And it's not too verbose to be used as it is in case I want to extract strings both with and without delimiters in a uniform way.

            – Andriy M
            May 6 at 12:34
















          7














          Depending on your actual XML structure you could consider using a loop like this:



          DECLARE @xml XML

          SELECT @xml = '<R>
          <I>A</I>
          <I>B</I>
          <I>C</I>
          <J>X</J>
          <J>Y</J>
          <J>Z</J>
          </R>'

          SELECT
          Tbl.Col.query('for $i in I return $i').value('.', 'nvarchar(max)'),
          Tbl.Col.query('for $i in J return $i').value('.', 'nvarchar(max)')
          FROM @xml.nodes('R') Tbl(Col);


          which outputs this:



          (No column name) | (No column name) 
          --------------- | ---------------
          ABC | XYZ


          See this fiddle






          share|improve this answer



















          • 1





            This is really good. I can easily adapt it to include delimiters whenever I need to. And it's not too verbose to be used as it is in case I want to extract strings both with and without delimiters in a uniform way.

            – Andriy M
            May 6 at 12:34














          7












          7








          7







          Depending on your actual XML structure you could consider using a loop like this:



          DECLARE @xml XML

          SELECT @xml = '<R>
          <I>A</I>
          <I>B</I>
          <I>C</I>
          <J>X</J>
          <J>Y</J>
          <J>Z</J>
          </R>'

          SELECT
          Tbl.Col.query('for $i in I return $i').value('.', 'nvarchar(max)'),
          Tbl.Col.query('for $i in J return $i').value('.', 'nvarchar(max)')
          FROM @xml.nodes('R') Tbl(Col);


          which outputs this:



          (No column name) | (No column name) 
          --------------- | ---------------
          ABC | XYZ


          See this fiddle






          share|improve this answer













          Depending on your actual XML structure you could consider using a loop like this:



          DECLARE @xml XML

          SELECT @xml = '<R>
          <I>A</I>
          <I>B</I>
          <I>C</I>
          <J>X</J>
          <J>Y</J>
          <J>Z</J>
          </R>'

          SELECT
          Tbl.Col.query('for $i in I return $i').value('.', 'nvarchar(max)'),
          Tbl.Col.query('for $i in J return $i').value('.', 'nvarchar(max)')
          FROM @xml.nodes('R') Tbl(Col);


          which outputs this:



          (No column name) | (No column name) 
          --------------- | ---------------
          ABC | XYZ


          See this fiddle







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered May 6 at 12:19









          Tom VTom V

          14.1k74880




          14.1k74880








          • 1





            This is really good. I can easily adapt it to include delimiters whenever I need to. And it's not too verbose to be used as it is in case I want to extract strings both with and without delimiters in a uniform way.

            – Andriy M
            May 6 at 12:34














          • 1





            This is really good. I can easily adapt it to include delimiters whenever I need to. And it's not too verbose to be used as it is in case I want to extract strings both with and without delimiters in a uniform way.

            – Andriy M
            May 6 at 12:34








          1




          1





          This is really good. I can easily adapt it to include delimiters whenever I need to. And it's not too verbose to be used as it is in case I want to extract strings both with and without delimiters in a uniform way.

          – Andriy M
          May 6 at 12:34





          This is really good. I can easily adapt it to include delimiters whenever I need to. And it's not too verbose to be used as it is in case I want to extract strings both with and without delimiters in a uniform way.

          – Andriy M
          May 6 at 12:34











          0














          If your elements and values really are short and distinct this works:



          declare @s varchar(99) = '<R><I>A</I><I>B</I><I>C</I></R>';

          select
          @s,
          REPLACE(TRANSLATE ( @s, '<>I/R', ' '), ' ', '');


          For non-trivial XML it may struggle, though.






          share|improve this answer
























          • The elements can be short, but the values in general are not, and I can't be sure they won't contain same characters as the element names do. Appreciate the outside the box approach, though.

            – Andriy M
            May 7 at 8:28
















          0














          If your elements and values really are short and distinct this works:



          declare @s varchar(99) = '<R><I>A</I><I>B</I><I>C</I></R>';

          select
          @s,
          REPLACE(TRANSLATE ( @s, '<>I/R', ' '), ' ', '');


          For non-trivial XML it may struggle, though.






          share|improve this answer
























          • The elements can be short, but the values in general are not, and I can't be sure they won't contain same characters as the element names do. Appreciate the outside the box approach, though.

            – Andriy M
            May 7 at 8:28














          0












          0








          0







          If your elements and values really are short and distinct this works:



          declare @s varchar(99) = '<R><I>A</I><I>B</I><I>C</I></R>';

          select
          @s,
          REPLACE(TRANSLATE ( @s, '<>I/R', ' '), ' ', '');


          For non-trivial XML it may struggle, though.






          share|improve this answer













          If your elements and values really are short and distinct this works:



          declare @s varchar(99) = '<R><I>A</I><I>B</I><I>C</I></R>';

          select
          @s,
          REPLACE(TRANSLATE ( @s, '<>I/R', ' '), ' ', '');


          For non-trivial XML it may struggle, though.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered May 7 at 7:53









          Michael GreenMichael Green

          15.1k83263




          15.1k83263













          • The elements can be short, but the values in general are not, and I can't be sure they won't contain same characters as the element names do. Appreciate the outside the box approach, though.

            – Andriy M
            May 7 at 8:28



















          • The elements can be short, but the values in general are not, and I can't be sure they won't contain same characters as the element names do. Appreciate the outside the box approach, though.

            – Andriy M
            May 7 at 8:28

















          The elements can be short, but the values in general are not, and I can't be sure they won't contain same characters as the element names do. Appreciate the outside the box approach, though.

          – Andriy M
          May 7 at 8:28





          The elements can be short, but the values in general are not, and I can't be sure they won't contain same characters as the element names do. Appreciate the outside the box approach, though.

          – Andriy M
          May 7 at 8:28


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Database Administrators Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f237475%2fconcatenate-all-values-of-the-same-xml-element-using-xpath-xquery%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          He _____ here since 1970 . Answer needed [closed]What does “since he was so high” mean?Meaning of “catch birds for”?How do I ensure “since” takes the meaning I want?“Who cares here” meaningWhat does “right round toward” mean?the time tense (had now been detected)What does the phrase “ring around the roses” mean here?Correct usage of “visited upon”Meaning of “foiled rail sabotage bid”It was the third time I had gone to Rome or It is the third time I had been to Rome

          Bunad

          Færeyskur hestur Heimild | Tengill | Tilvísanir | LeiðsagnarvalRossið - síða um færeyska hrossið á færeyskuGott ár hjá færeyska hestinum