使用 XmlSerializer 反序列化 XML 文档失败

Deserialize XML Document Fails Using XmlSerializer

我正在使用 XmlSerializer 序列化和反序列化 XML 文档。

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

这就是我序列化 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();
}

这就是我反序列化的方式,也是我得到错误的地方,外部异常是

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

,内部异常是

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

这是 XML 文档

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

类型不匹配,(在反序列化过程中)应该是:

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

我不久前写了这个并且经常使用它。使用泛型,您可以对 XML 进行序列化和反序列化。请记住,有些对象不能像字典那样被序列化。 XmlSerializer<T> 不是 "catch all",如果需要,您可能需要修改以执行更多操作。

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

并使用:

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