开发者

C# XML Serialization/DeSerialization [closed]

开发者 https://www.devze.com 2023-02-25 07:19 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 9 years ago.

I'm having a look at XML Serialization and have serialized as such:

public static string Serialize<T>(T data)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    //Overridden to use UTF8 for compatability with Perl XML::DOM
    StringWriterUTF8 sw = new StringWriterUTF8();
    xmlSerializer.Serialize(sw, data);
    return sw.ToString();
}

I use it as such:

string serializedData = Serializer.Serialize<List<InputData>>(rawDataCollection);

Which produces:

<ArrayOfInputData xmlns:xsi="http://www.w3.org/2001/XMLSchema-                instance"                 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <InputDat开发者_如何学Goa>
        <dose>100mg/kg</dose> 
        <compound>AZ13279746-001</compound> 
    </InputData>
</ArrayOfInputData>

For some reason, I can't include the header which was xml version 1.0 encoding UTF8.

Now, when I try to deserialize with

public static object DeSerialize<T>(string data)
{
    StringReader rdr = new StringReader(data);
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    T i;
    i = (T)xmlSerializer.Deserialize(rdr);

    return i;
}

I get an error saying invalid xml at 2,2. Any idea what I am doing wrong?

Thanks


Have now fixed it:

public static object DeSerialize<T>(string data)
    {

       StringReader rdr = new StringReader(data);

       XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));


       var result = (T)xmlSerializer.Deserialize(rdr);


       return result; 



    }

var fl = (List<InputData>)Serializer.DeSerialize<List<InputData>>(serializedData);


Not sure if it's a typo, or a genuine mistake in the output, but you have an erroneous space in your XML.

< /ArrayOfInputData>
0

精彩评论

暂无评论...
验证码 换一张
取 消