Convert string into XML

1

Consider the table:

In code behind, I can not convert a string to an xml

  modCamadaOperacao objModCamada = new modCamadaOperacao();
  objModCamada.idCamadaOperacao = idCamada; 
  objModCamada.xmlCamadaOperacao = serializer.Xml; // XML_CAMADA_OPERACAO

In case the string is serializer.Xml

The error that returns is:

  

Can not implicit convert type string to system.Xml.XmlDocument

    
asked by anonymous 17.09.2018 / 22:48

1 answer

2

Try using this conversion.

public static class Serializa
{
    public static string SerializaParaString<T>(this T valor)
    {
        XmlSerializer xml = new XmlSerializer(valor.GetType());
        StringWriter retorno = new StringWriter();
        xml.Serialize(retorno, valor);
        return retorno.ToString();
    }

    public static object DeserializaParaObjeto(string valor, Type tipo)
    {
        XmlSerializer xml = new XmlSerializer(tipo);
        var valorSerealizado = new StringReader(valor);
        return xml.Deserialize(valorSerealizado);
    }
}

Conversion methods call:

class Program
{
    static void Main(string[] args)
    {
        var stringParaSerializar = "Frase Qualquer";

        var valor = Serializa.SerializaParaString(stringParaSerializar);

        Console.WriteLine(valor);

        Console.ReadKey();
    }
}

Result:

<?xml version="1.0" encoding="utf-16"?>
<string>Frase Qualquer</string>
  

More information on serializing and deserializing XML objects to string: C # - Serializing Objects to String and vice versa

    
17.09.2018 / 23:33