我已经反序列化了一个xml文件,其中包含程序列表,日期,时间以及对它们的真或假值。该文件类似于下面的内容。
<AlarmSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ProgramSettings>
<ProgramSetting>
<ProgramPathText>Alarm.exe</ProgramPathText>
<ProgramPathValue>D:\Documents\Work\Visual Studio\WindowsFormsApplication1\bin\Debug\Alarm.exe</ProgramPathValue>
<Monday>
<Time>11:08</Time>
<Enabled>true</Enabled>
</Monday>
<Tuesday>
<Time>17:08</Time>
<Enabled>true</Enabled>
</Tuesday>
</ProgramSetting>
</ProgramSettings>
</AlarmSettings>
我正在尝试访问这些值,但我一直在程序设置结束时卡住,我无法看到任何有用的方法。我需要返回programpathtext值,programpathvalue值等。
public void load()
{
AlarmSettings alarmSettings;
alarmSettings = AlarmSettings.Load(@"C:\Users\jason\Desktop\Booya.txt");
alarmSettings.ProgramSettings.
}
任何帮助将不胜感激。感谢
AlarmSettings Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
namespace WindowsAlarm
{
public class AlarmSettings
{
public List<ProgramSetting> ProgramSettings = new List<ProgramSetting>();
public void Save(string filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(AlarmSettings));
TextWriter writer = new StreamWriter(filename);
serializer.Serialize(writer, this);
writer.Close();
}
public static AlarmSettings Load(string filename)
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(AlarmSettings));
using (StreamReader reader = new StreamReader(filename))
{
AlarmSettings loadedSettings = (AlarmSettings)serializer.Deserialize(reader);
reader.Close();
return loadedSettings;
}
}
catch(Exception e)
{
throw e;
//return new AlarmSettings();
}
}
}
}
答案 0 :(得分:1)
如果你有适当的对象结构,请使用XmlSerializer
XmlSerializer serializer = new XmlSerializer(typeof(objecttype));
或使用Linq to XML或创建自己的XML解析器,你可以在Google上搜索
您还可以查看有关序列化的帖子:Object to XML using LINQ or XmlSerializer
答案 1 :(得分:0)
我已经解决了这个问题。问题是我没有进入并访问该集合。
public void load()
{
AlarmSettings alarmSettings;
alarmSettings = AlarmSettings.Load(@"C:\Users\jason\Desktop\Booya.txt");
foreach (var setting in alarmSettings.ProgramSettings)
{
string pathtext = setting.ProgramPathText;
string pathvalue = setting.ProgramPathValue;
}
}