将XML相同的标记名称值读取到类列表中

时间:2014-11-10 06:49:57

标签: c# xml

我想使用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()错误

有人知道怎么做吗?

0 个答案:

没有答案