Joe Stellato
Joe Stellato

Reputation: 568

Deserialize XML Document Fails Using XmlSerializer

I'm using XmlSerializer to serialize and deserialize an XML Document.

public class FolderPath
{
    public string Path { get; set; }
}

This is how I am Serializing the class:

private static void UpdateFolderPathsXml(List<FolderPath> folderPaths,
string fileName = "FolderPaths.xml")
{
    XmlSerializer x = new XmlSerializer(folderPaths.GetType());

    TextWriter writeFileStream = new StreamWriter(fileName);
    x.Serialize(writeFileStream, folderPaths);
    writeFileStream.Close();
}

This is how I Deserialize, and also where I get the error, Outer Exception is

There is an error in XML document (2, 2)

, and inner exception is

ArrayOfFolderPath xmlns='' was not expected.

XmlSerializer x = new XmlSerializer(typeof (FolderPath));
using (FileStream reader = new FileStream(fileName, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
    // This is the line that shows the exception
    var readPathList = (List<FolderPath>)x.Deserialize(reader);
}

This is the XML Document

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfFolderPath xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FolderPath>
    <Path>c:\FolderA</Path>
  </FolderPath>
</ArrayOfFolderPath>

Upvotes: 1

Views: 2273

Answers (2)

PhillyNJ
PhillyNJ

Reputation: 3903

I wrote this a while ago and use it a lot. Using generics you can serialize and deserialize to and from XML. Keep in mind, that some objects can not be serierized like Dictionaries. The XmlSerializer<T> is not a "catch all", you may need to modified to do more if needed.

public class XmlSerializer<T>
{
    /// <summary>
    /// Load a Xml File and Deserialize into and object         
    /// </summary>
    /// <param name="xml">Xml String</param>
    /// <returns>Object representing the xml.</returns>
    public T DeserializeXml(String xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));

        T obj;
        using (StringReader reader = new StringReader(xml))
        {
            obj = (T)serializer.Deserialize(reader);
        }
        return obj;


    }
    /// <summary>
    /// Serialize an Object to a Xml String
    /// </summary>
    /// <param name="obj">Any Object</param>
    /// <returns>Xml String</returns>
    public String SerializeXml(T obj)
    {

        XmlSerializer serializer = new XmlSerializer(obj.GetType());

        using (StringWriter writer = new StringWriter())
        {
            serializer.Serialize(writer, obj);

            return writer.ToString();
        }

    }


    /// <summary>
    /// Converts object T to a xml string with no prolog
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public String SerializeToXmlString(T obj)
    {
        var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
        var serializer = new XmlSerializer(obj.GetType());
        var settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;

        using (var stream = new StringWriter())
        using (var writer = XmlWriter.Create(stream, settings))
        {
            serializer.Serialize(writer, obj, emptyNamepsaces);
            return stream.ToString();
        }
    }
}

And to use:

class Program
{
        static void Main(string[] args)
        {
            String xmlPath = @"C:\Users\Desktop\example.xml";
            List<FolderPath> paths = new List<FolderPath>();
            paths.Add(new FolderPath { Path = "c:/temp" });

            XmlSerializer<List<FolderPath>> ser = new XmlSerializer<List<FolderPath>>();
            String xml = System.IO.File.ReadAllText(xmlPath);
            List<FolderPath> testDeserializeXml = ser.DeserializeXml(xml);
            var serializeToXmlString = ser.SerializeToXmlString(paths);


        }
}

public class FolderPath
{
    public string Path { get; set; }
}

Upvotes: 0

kennyzx
kennyzx

Reputation: 12993

Type mismatched, (during deserialization) it should be:

XmlSerializer x = new XmlSerializer(typeof(List<FolderPath>));

Upvotes: 2

Related Questions