4

If i wanted to add an attribute to the root element record, can i do this from the sql side?

SELECT top 1 'text' as nodeA
                from test as z
FOR XML AUTO, ELEMENTS, root('record')

i would like to produce the xml like this:

 <Root attribute="value">
     <z>
         <NodeA>text</NodeA>
     </z>
 </Root>
4
  • Can you show what your table looks like, and what you want your XML to look like?? Commented Dec 7, 2011 at 20:10
  • @mar_s hi marc, i added an update Commented Dec 7, 2011 at 21:02
  • Updated my response to satisfy your requirement .... Commented Dec 7, 2011 at 21:29
  • 1
    @marc_s woops, i forgot to mark as answer, thanks marc! Commented Dec 7, 2011 at 21:53

3 Answers 3

8

Use the new FOR XML PATH syntax:

SELECT TOP 1 
   'someValue' AS '@Attribute',
   'text' as 'z/NodeA'
FROM dbo.Test
WHERE....
FOR XML PATH('YourElement'), ROOT('Root')

This would give something like

<Root>
   <YourElement Attribute="someValue">
      <z>
         <NodeA>text</NodeA>
      </z>
   </YourElement>
</Root>

Read more about it here:

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

Comments

1

Your example is not doing what is requested.

request:

<Root attribute="someValue">
   <YourElement>
      <z>
         <NodeA>text</NodeA>
      </z>
   </YourElement>
</Root>

your answer:

<Root>
   <YourElement Attribute="someValue">
      <z>
         <NodeA>text</NodeA>
      </z>
   </YourElement>
</Root>

I'm doing something similar and using PowerShell to scrub the file before saving it:

scrub reason 1: https://connect.microsoft.com/SQLServer/feedback/details/265956/suppress-namespace-attributes-in-nested-select-for-xml-statements

scrub reason 2: THIS

1 Comment

It seems that you forgot the link for scrub reason 2.
0
SELECT 
      'someValue' AS '@Attribute',
      (SELECT TOP 1 
              'text' as 'z/NodeA'
               FROM dbo.Test
               WHERE....
               FOR XML PATH('YourElement')
       ) 
FOR XML PATH('ROOT');

It should create a xml with ROOT containg attribute and list of ... inside.

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.