XML序列化到文件

时间:2015-05-19 09:51:24

标签: c# xml xml-serialization xmlserializer

我想实现以下目标:

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

使用以下bool属性

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

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

XmlSerializer.Deserialize()崩溃了。该属性是否必须是一个数组而不是bool?我想保留boolean属性,所以请建议使用XML属性。

2 个答案:

答案 0 :(得分:1)

从MSDN:您可以将XmlArrayAttribute应用于返回对象数组的公共字段或读/写属性。您还可以将它应用于返回ArrayList的集合和字段或任何返回实现IEnumerable接口的对象的字段。

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

使用bool数组或手动序列化/反序列化。

答案 1 :(得分:1)

试试这个

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

}