Jessai
Jessai

Reputation: 947

SqlXml removes XML header when comes from string

I'm developing a web app with C# and MVC4. Currently I'm working in converting string vars to SqlXml files. I have a XML file with this structure:

<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/TimbreFiscalDigital/TimbreFiscalDigital.xsd" xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital" version="3.2" xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</cfdi:Comprobante>

I'm converting the above file to string successfully and then I'm usign the following code that converts a string to a SqlXML.

cfdiDocumento.CFDIXML = Serializar.XMLToSqlXml(comprobante);

Where cfdiDocumento.CFDIXML is a SqlXml var, Serializar.XMLToSqlXml(comprobante) method receives a string and executes the following code:

    public static SqlXml XMLToSqlXml(string xmlString)
    {
        SqlXml sqlXmlFiltro = null;
        if (xmlString != null)
        {
            StringReader sr = new StringReader(xmlString);
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ConformanceLevel = ConformanceLevel.Auto;
            XmlReader reader0 = XmlReader.Create(sr, settings);
            sqlXmlFiltro = new SqlXml(reader0);
        }

        return sqlXmlFiltro;
    }

When the code finishes successfully, the file is correct but is removing the xml header

<?xml version="1.0" encoding="utf-8"?>

The question is: How do I preserve the xml header when convierting to SqlXml var?

Upvotes: 2

Views: 303

Answers (1)

To&#241;o L&#243;pez
To&#241;o L&#243;pez

Reputation: 26

If you cannot change the type of your SqlXml attribute, you could try converting the SqlXml to xml document to append xml declaration and get the outer xml:

public string SqlXmlToString(SqlXml sqlXml)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(sqlXml.CreateReader());

    // Create XML declaration with your encoding. 
    XmlDeclaration xmldecl;
    xmldecl = doc.CreateXmlDeclaration("1.0", null, null);
    xmldecl.Encoding = "UTF-8";

    // Add to the document the created declaration
    XmlElement root = doc.DocumentElement;
    doc.InsertBefore(xmldecl, root);

    return doc.OuterXml;
}

Hope this is helpfully

Upvotes: 1

Related Questions