XML 序列化到文件

XML Serialisation to file

我想实现以下目标:

<?xml version="1.0" encoding="utf-8"?>
<StatisticsFunctionsSetting xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <StatisticsFunctions>
    <Visibility>false</Visibility>
  </StatisticsFunctions>
</StatisticsFunctionsSetting>

使用以下布尔值 属性

[XmlArray("StatisticsFunctions")]
[XmlArrayItem("Visibility")]
public bool IsShowChecked
{
    get
    {
        return this.isShowChecked;
    }

    set
    {
        this.isShowChecked = value;
        this.OnPropertyChanged("IsShowChecked");
    }
}

它在 XmlSerializer.Deserialize() 崩溃。 属性 必须是数组而不是布尔值吗?我想保留布尔值 属性,所以请建议使用 XML 属性。

来自 MSDN:您可以将 XmlArrayAttribute 应用于 public 字段或 read/write 属性 return 对象数组。您还可以将其应用于 return ArrayList 的集合和字段或 return 实现 IEnumerable 接口的对象的任何字段。

https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayattribute%28v=vs.110%29.aspx

使用布尔数组或手动数组serialize/deserialize。

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"C:\temp\test.xml";
        static void Main(string[] args)
        {
            StatisticsFunctionsSetting settings = new StatisticsFunctionsSetting(){
                statisticsFunctions = new List<StatisticsFunctions>(){
                    new StatisticsFunctions(){
                        visibility = new List<bool>(){true,true, false}
                    }
                }
            };

            XmlSerializer serializer = new XmlSerializer(typeof(StatisticsFunctionsSetting));

            StreamWriter writer = new StreamWriter(FILENAME);
            XmlSerializerNamespaces _ns = new XmlSerializerNamespaces();
            _ns.Add("", "");
            serializer.Serialize(writer, settings, _ns);
            writer.Flush();
            writer.Close();
            writer.Dispose();

            XmlSerializer xs = new XmlSerializer(typeof(StatisticsFunctionsSetting));
            XmlTextReader reader = new XmlTextReader(FILENAME);
            StatisticsFunctionsSetting  newSettings = (StatisticsFunctionsSetting)xs.Deserialize(reader);


        }
    }

    [XmlRoot("StatisticsFunctionsSetting")]
    public class StatisticsFunctionsSetting
    {
        [XmlElement("StatisticsFunctions")]
        public List<StatisticsFunctions> statisticsFunctions {get;set;}
    }
    [XmlRoot("StatisticsFunctions")]
    public class StatisticsFunctions
    {
        [XmlElement("Visibility")]
        public List<Boolean> visibility { get; set; }
    }

}