繁体   English   中英

C#:如何从反序列化的xml文件访问数据

[英]C#: How do i access data from a deserialized xml-file

我已经设置了xml-serialization / deserialization以将数据保存在应用程序中。 我可以反序列化非数组元素,但是当我反序列化数组时,它为空。 我有一个预感,问题出在属性的设置部分中,我试图进行序列化/反序列化。

首先,我要序列化的类:

namespace kineticMold
{
    [Serializable()]
    public class Config
    {
        public Config() { }
        public string ComPort
        {
            get
            {
                return comPort;
            }
            set
            {
                comPort = value;
            }
        }

        [XmlArrayItem("recentFile")]
        public string[] LastOpen
        {

            get
            {
                return lastOpen;
            }
            set
            {

                    ArrayList holderList = new ArrayList();

                    holderList.Add(value);

                    for (int i = 0; i < 4; i++)
                    {

                        holderList.Add(lastOpen[i]);

                    }

                    lastOpen = (string[])lastOpen.ToArray<string>();



            }
        }

        private string comPort;
        private string[] lastOpen = new string[5];


    }
}

序列化的结果:

<?xml version="1.0" encoding="utf-8" ?> 
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <ComPort>COM12</ComPort> 
    <LastOpen>
       <recentFile>test.xml</recentFile> 
       <recentFile xsi:nil="true" /> 
       <recentFile xsi:nil="true" /> 
       <recentFile xsi:nil="true" /> 
       <recentFile xsi:nil="true" /> 
    </LastOpen>
</Config>

反序列化的代码:

_cf = new Config();
            XmlSerializer ser = new XmlSerializer(typeof(Config));

            if (File.Exists(settings_filepath))
            {
                FileStream fs = new FileStream(@settings_filepath, FileMode.Open);
                _cf = (Config)ser.Deserialize(fs);
                fs.Close();
            }

读取反序列化数据的代码:

 for (int i = 0; i < _cf.LastOpen.Length; i++)
            {

                if (_cf.LastOpen[i] != null)
                {
                    toolStripMenuItem1.DropDownItems.Add(_cf.LastOpen[i]);

                    recentState = true;
                }
            }

你有:

lastOpen = (string[])lastOpen.ToArray<string>();

您的意思是这里的holderList (在右侧)吗?

这是不完全清楚你想要的数据,但目前不保留任何项目从value超越制定者。 同样, ArrayList在这里是多余的。 可能是List<string>

当然,甚至更简单:

private readonly List<string> lastOpen = new List<string>();
[XmlArrayItem("recentFile")]
public List<string> LastOpen {get {return lastOpen;}}

(并让调用代码担心其中要保留多少个项目)

暂无
暂无

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

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