Convert string to XML

Asked

Viewed 955 times

1

Consider the table:

inserir a descrição da imagem aqui

In the Behind code, I cannot convert a string into an xml

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

In this case the string is the serializer.Xml

the error that returns is:

Cannot implicity Convert type string to system.xml.Xmldocument

  • 1

    Those who are negative please speak up, because I see no reason for this.

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

Call for conversion methods:

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

        var valor = Serializa.SerializaParaString(stringParaSerializar);

        Console.WriteLine(valor);

        Console.ReadKey();
    }
}

Upshot:

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

More information about serializing and deserializar XML objects to string: C# - Serializing Objects for String and vice versa

Browser other questions tagged

You are not signed in. Login or sign up in order to post.