我想使用XML
向类中读取C#
个标签。这是我的XML
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<setting>
<autosave onoff="false" minute="10"/>
<catpriority category="false"/>
<autobackup onoff="false" backuppath="c:\"/>
</setting>
<database>
<db dbid="0" conn="" writer="" active="true" />
<db dbid="1" conn="" writer="" active="false" />
<db dbid="2" conn="" writer="" active="false" />
</database>
</configuration>
我创建了两个类来保存XML
值。
public class Configuration
{
public bool SaveOnoff { get; set; }
public string Minute { get; set; }
public bool Category { get; set; }
public bool BackupOnoff { get; set; }
public string Backuppath { get; set; }
public List<Db> DbList =new List<Db>();
}
public class Db
{
public int Dbid { get; set; }
public string Conn { get; set; }
public string Writer { get; set; }
public bool Active { get; set; }
}
我使用以下代码阅读XML
值:
private Configuration Config = new Configuration();
var res =Assembly.GetAssembly(typeof (Configuration))
.GetManifestResourceStream("mynamespace.Resources.Configuration.xml");
var xReader = new XmlTextReader(res);
XDocument loadedCustomData = XDocument.Load(xReader);
var filteredData = from c in loadedCustomData.Descendants("autosave")
select new Configuration()
{
SaveOnoff = Convert.ToBoolean(c.Attribute("onoff").Value),
Minute = c.Attribute("minute").Value,
};
Config.SaveOnoff = filteredData.First().SaveOnoff;
Config.Minute = filteredData.First().Minute;
但我无法弄清楚如何将<db> tag
值读取到我的Db Class
并将其添加到我的Configuration Class
实例中。这就是我到目前为止所做的:
filteredData = from c in loadedCustomData.Descendants("db")
select new Configuration()
{
DbList = new List<Db>
{
new Db
{
Dbid = Convert.ToInt32(c.Attribute("dbid").Value),
Conn = c.Attribute("conn").Value,
Writer = c.Attribute("writer").Value,
Active = Convert.ToBoolean(c.Attribute("active").Value)
}
}
};
foreach (Configuration conf in filteredData)
{
//Db newDb = new Db { Dbid = Convert.ToInt32(conf.Value) };
Config.DbList.Add(conf.DbList[0]);
//Config.DbList.Add(new Db{Active=conf.Active,Conn = conf.Conn,Dbid = conf.Dbid,DbOnoff = conf.DbOnoff,Englishname = conf.Englishname,Persianname = conf.Persianname,Writer = conf.Writer});
}
foreach
按时循环,下一个循环在Object reference not set to an instance of an object.
select new Configuration()
错误
有人知道怎么做吗?