如何处理XML序列化/反序列化中的默认设置?

时间:2014-05-01 22:28:40

标签: c# .net xml

我尝试创建默认设置是不行的,当我从XML文件反序列化对象时,我会重复那些不应该存在的条目。但是第一次写入XML时,我得到了正确的数字

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            ConfigurationData a = Config.GetConfigData();

            ConfigurationData c = new ConfigurationData();
            Config.SaveConfigData(c);
        }
    }


    public static class Config
    {
        #region Default Data

        public static List<ProductType> PRODType = new List<ProductType>();

        private static ProductType PRODType1;
        private static ProductType PRODType2;

        // name of the .xml file
        private static string CONFIG_FNAME = "config.xml";

        public static void GetDefaultConfig()
        {

            PRODType1 = new ProductType();
            PRODType1.PRODType = "P1";
            PRODType1.Item = new ProductItem();
            PRODType1.Item.Name = "product1";
            PRODType1.Item.Path = @"\test\test";

            PRODType2 = new ProductType();
            PRODType2.PRODType = "P2";

            PRODType.Add(PRODType1);
            PRODType.Add(PRODType2);

        }

        #endregion



        public static ConfigurationData GetConfigData()
        {
            if (!File.Exists(CONFIG_FNAME)) // create config file with default values
            {
                using (FileStream fs = new FileStream(CONFIG_FNAME, FileMode.Create))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(ConfigurationData));
                    ConfigurationData sxml = new ConfigurationData();
                    xs.Serialize(fs, sxml);
                    return sxml;
                }
            }
            else // read configuration from file
            {
                using (FileStream fs = new FileStream(CONFIG_FNAME, FileMode.Open))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(ConfigurationData));
                    ConfigurationData sc = (ConfigurationData)xs.Deserialize(fs);
                    return sc;
                }
            }
        }

        public static bool SaveConfigData(ConfigurationData config)
        {
            if (!File.Exists(CONFIG_FNAME)) return false; // don't do anything if file doesn't exist

            using (FileStream fs = new FileStream(CONFIG_FNAME, FileMode.Open))
            {
                XmlSerializer xs = new XmlSerializer(typeof(ConfigurationData));
                xs.Serialize(fs, config);
                return true;
            }
        }


    }

    // this class holds configuration data
    public class ConfigurationData
    {
        public List<ProductType> ProductTypes;

        public ConfigurationData()
        {
            Config.GetDefaultConfig();
            ProductTypes = Config.PRODType;
        }
    }


    public class ProductType
    {
        [XmlAttribute("Value")]
        public string PRODType { get; set; }

        public ProductItem Item { get; set; }
    }


    public class ProductItem
    {
        [XmlAttribute("Name")]
        public string Name { get; set; }

        [XmlAttribute("Path")]
        public string Path { get; set; }

        [XmlAttribute("Attribute")]
        public string Attribute { get; set; }

    }
}

1 个答案:

答案 0 :(得分:0)

利用ConfigurationManager库,该库将读取XML文件并查找特定标签,例如“appSettings”,并且可以轻松地从中读取和写入。

创建结构如下的XML:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
   </configSections>

   <appSettings>
      <add key="ClientId" value="5017" />
      <add key="LocationCode" value="01"/>
   </appSettings>
</configuration>

然后您可以使用代码(WinForms应用程序中的示例)进行读写,例如:

MyConfig = ConfigurationManager.OpenExeConfiguration _
                                         (ConfigurationUserLevel.None)

MyConfig.AppSettings.Settings("ClientId").Value = txtClientId.Text
MyConfig.AppSettings.Settings("LocationCode").Value = txtLocation.Text
MyConfig.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")

我概述了如何轻松完成这项工作here