我正在使用C#和MVC4开发Web应用程序。目前,我正在将字符串vars转换为SqlXml文件。我有一个具有以下结构的XML文件:

<?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>


我将上述文件成功转换为字符串,然后使用下面的代码将字符串转换为SqlXML。

cfdiDocumento.CFDIXML = Serializar.XMLToSqlXml(comprobante);


cfdiDocumento.CFDIXML是SqlXml变量,而Serializar.XMLToSqlXml(comprobante)方法接收字符串并执行以下代码:

    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;
    }


代码成功完成后,文件正确但正在删除xml标头

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


问题是:转换为SqlXml var时如何保留xml标头?

最佳答案

如果您无法更改SqlXml属性的类型,则可以尝试将SqlXml转换为xml文档以追加xml声明并获取外部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;
}


希望这会有所帮助

10-07 17:30