Search code examples
sql-serverxmlsql-server-2005for-xml

Truly empty element with sql server for xml-directive


How do I create a truly empty xml element with the for xml-directive in sql server (2005)?

Example:

select
    ''
for xml path('element'), root('elements')

Outputs:

<elements><element></element></elements>

But what I really want is:

<elements><element /></elements>

Solution

  • Add the type directive and then run it in a subquery.

    Like this:

    select
    (
        select
            ''
        for xml path('element'), type
    )
    for xml path('elements')