Search code examples
c#sql-serverxmlsql-server-2012sqlclr

Quick way SqlXml to XmlDocument in C# for a SQLCLR function?


Which is better way to load SqlXml into XmlDocument (if any) without intermediate string?

I need to validate xml using xsd from database inside CLR UDF. I try to optimize my code.

My code is:

        schema1 = XmlSchema.Read(new StringReader(cXmlSchemaText), ValidateSchema);

        asset1.Schemas.Add(schema1);
        asset1.LoadXml(ValueString.ToString());
        asset1.Validate(ValidateXmlValue);

where ValueString is my SqlXml.


Solution

  • First, even with .ToString() and .Value returning the same string value, it is probably best to use ValueString.Value for the sake of consistency in terms of accessing values within the Sql* types.

    You should be able to skip the intermediate string by using the SqlXml.CreateReader method which should, according to the documentation, be returning the internal XmlReader of the SqlXml variable. Your code would change very slightly to be:

    asset1.Load(ValueString.CreateReader());