SQL Server 2005 XML type looses spaces

Hi all,

I am using ADO.NET 2.0 to store an XML string into a SQL Server 2005 xml field. The code is shown below.

When an element contains only spaces, it is stored as an empty element in SQL Server 2005. For example,

<Str> </Str>

is stored in SQL 2005 as

<Str />

I've read Denis Ruckebush's post about this at http://blogs.msdn.com/denisruc/archive/2005/09/12/464145.aspx. However, using CONVERT is not an option, as the data is stored without the application framework actually knowing that it is an XML field.

Are there any other workarounds for this

Thanks,

SA.

Code:

Data data = new Data();

data.Str = " ";

XmlSerializer serializer = new XmlSerializer(typeof(Data));

System.IO.TextWriter tw = new System.IO.StringWriter();

serializer.Serialize(tw, data);

System.IO.StringWriter sw = (System.IO.StringWriter)tw;

string XmlString = sw.ToString();

Console.WriteLine(XmlString);

SqlConnection Conn = new SqlConnection(@"server=(local)\SQLEXP2005;database=Test;integrated security=sspi;");

Conn.Open();

SqlCommand cmd = new SqlCommand("INSERT INTO XmlSpace01 VALUES (@XmlData)", Conn);

SqlParameter param = new SqlParameter("@XmlData", XmlString);

param.Direction = System.Data.ParameterDirection.Input;

param.DbType = System.Data.DbType.Xml;

cmd.Parameters.Add(param);

cmd.ExecuteNonQuery();



Answer this question

SQL Server 2005 XML type looses spaces

  • Eric Larson

    I don't suppose you have enough control of the XML to put the spaces in a CDATA section like this example

    declare @var XML
    SET
    @var = '
    <root>
    <a>
    <b>Data b</b>
    </a>
    <c><![CDATA[ ]]></c>
    </root>'
    SELECT @var
    go



  • deepika

    Jeff,

    No, I don't have enough control over that.

    However, I am working on a solution that involves modifying the insert and update commands to include the CONVERT function for xml fields.

    It works like this

    INSERT INTO [TEST] VALUES (CONVERT(xml, @field, 1));

    Thanks for your reply though.

    SA.


  • SQL Server 2005 XML type looses spaces