简体   繁体   English

C#中的XmlSerializer /反序列化

[英]XmlSerializer/Deserialize in C#

I created this class where it'll append to the XML called Email Alerts h1, body and ids. 我创建了该类,该类将附加到名为“电子邮件警报” h1,body和id的XML上。 However, im having trouble running this file from the start (when i call LoadFromFile), when the file does not exist - so we'll have to create a file and start logging it. 但是,当文件不存在时,从头开始运行该文件时(当我调用LoadFromFile时)遇到了麻烦-因此我们必须创建一个文件并开始对其进行记录。

public class EMailAlert
{
    public string h1 { get; set; }
    public string body { get; set; }
    public string idList { get; set; }

    public void Save(string fileName)
    {
        using (var stream = new FileStream(fileName, FileMode.Create))
        {
            var XML = new XmlSerializer(typeof(EMailAlert));
            XML.Serialize(stream, this);
        }
    }

    public static EMailAlert LoadFromFile(string fileName)
    {
        if (!File.Exists(fileName))
        {
            var file = new FileInfo(fileName);
            file.Directory.Create();
            var xmlFile = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XComment("Email Logger"));
            xmlFile.Add(new XElement("EmailAlerts"));
            xmlFile.Save(fileName);
        }
        using (var stream = new FileStream(fileName, FileMode.Open))
        {
            var XML = new XmlSerializer(typeof(EMailAlert));
            return (EMailAlert)XML.Deserialize(stream);
        }
    }
}

When i run this code (there are no xml file - so it creates an XML file and then it throws this error {"<EmailAlerts xmlns=''> was not expected."} 当我运行此代码时(没有xml文件-因此它创建了一个XML文件,然后引发了此错误{"<EmailAlerts xmlns=''> was not expected."}

Here is how the xml file looks like 这是xml文件的样子

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--Email Logger-->
<EmailAlerts />

Not sure why its not sending back an empty EmailAlert when i call LoadFromFile. 不知道为什么当我调用LoadFromFile时它没有发回空的EmailAlert。

You need a collectiontype for your all your EMailAlerts to be serialized as valid xml. 您需要将所有EMailAlerts序列化为有效xml的collectiontype。

The following code does that. 下面的代码可以做到这一点。 By creating a static helper class that holds a static List of all our EmailAlerts. 通过创建一个静态帮助器类,其中包含我们所有EmailAlerts的静态列表。 It also has the Load and Save methods which reads and writes the file and use the property Alerts to get or store the EmailAlerts. 它还具有Load和Save方法,该方法读取和写入文件,并使用Alerts属性获取或存储EmailAlerts。

You can use attributes on your EmailAlert class if you want to control serialization. 如果要控制序列化,可以在EmailAlert类上使用属性 See this answer how you could do that. 查看此答案 ,您将如何做到这一点。

public static class EMailAlerts
{
    static XmlSerializer   XML = new XmlSerializer(typeof(List<EMailAlert>));

    public static List<EMailAlert> Alerts { get; private set; }

    public static void Save(string fileName)
    {
        using (var stream = new FileStream(fileName, FileMode.Create))
        {
            XML.Serialize(stream, Alerts);
        }
    }

    public static void LoadFromFile(string fileName)
    {
        if (!File.Exists(fileName))
        {
            Alerts = new List<EMailAlert>();
        }
        else
        {
            using (var stream = new FileStream(fileName, FileMode.Open))
            {
                Alerts = (List<EMailAlert>)XML.Deserialize(stream);
            }
        }
    }
}

public class EMailAlert
{
    public string h1 { get; set; }
    public string body { get; set; }
    public string idList { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        EMailAlerts.LoadFromFile("tmp.xml");

        EMailAlerts.Alerts.Add(new EMailAlert{ body="foo"});
        EMailAlerts.Save("tmp.xml"); 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM