读取XML文件中的属性

时间:2012-07-10 18:48:09

标签: c# xml linq linq-to-xml

我正在尝试阅读如下文件:

<tasks>
  <task name="Project Management" mode="Automatic" start="07/01/2012 00:00" duration="21" id="954471332"></task>
  <task name="Conception/Approval" mode="Automatic" start="07/01/2012 00:00" duration="6" percentComplete="1" id="1905425539"></task>
  <task name="Define Initial Scope" start="07/04/2012 00:00" finish="07/18/2012 00:00" percentComplete="0.31" id="1154759651"></task>
</tasks>

我只想要namestartfinishduration的值,无论哪个存在。

这是我到目前为止所做的:

XElement allData = XElement.Load(dlg.FileName);
if (allData != null)
{
    IEnumerable<XElement> tasks = allData.Descendants("task");
    foreach (XElement task in tasks)
    {

    }
}

我确定我必须使用Attribute方法,但我不确定如何使用它或语法。

4 个答案:

答案 0 :(得分:1)

您可以这样做以获取属性:

XElement allData = XElement.Load(dlg.FileName);
if (allData != null)
{
    IEnumerable<XElement> tasks = allData.Descendants("task");
    foreach (XElement task in tasks)
    {
        task.Attribute("name").Value;
        task.Attribute("start").Value;
        task.Attribute("finish").Value;
    }
}

答案 1 :(得分:1)

我建议在循环之前只获取所需的元素和值:

XElement allData = XElement.Load(dlg.FileName);
if (allData != null)
{
  var tasks = allData.Descendants("task")
                     .Where(e => e.Attribute("name") != null
                                 && (e.Attribute("start") != null
                                     || e.Attribute("finish") != null))
                     .Select(e => new 
                     {
                       Name = e.Attribute("name").Value,
                       Start = e.Attribute("start").Value,
                       Finish = e.Attribute("finish").Value,
                     });
  foreach(var task in tasks)
  {
    // task.Name will have a value
    // task.Start and/or task.Finish will have a value.
  }
}

答案 2 :(得分:0)

假设你有一个对象任务,那么如何:

 XDocument doc = XDocument.Load(dlg.FileName);
  List<Task> infos = from c in doc.Descendants("task")
              select new Task (c.Element("name").Value, c.Element("start).Value, 
              c.Element("finish").Value);

答案 3 :(得分:0)

您可以这样做:

var doc = XDocument.Load(dlg.FileName);
var query = doc.Descendants("task")
    .Select(task => new
    {
        Name = (string)task.Attribute("name"),
        Start = (DateTime)task.Attribute("start"),
        Finish = (DateTime?)task.Attribute("finish"),
        Duration = (long?)task.Attribute("duration"),
    });

如果相应的属性不存在,FinishDuration字段将为null。

然后只需遍历查询中的项目即可。

foreach (var item in query)
{
    var app = c1Schedule1.DataStorage.AppointmentStorage.Appointments.Add();
    app.Subject = item.Name;
    app.Start = item.Start;
    if (item.Finish != null)
    {
        app.Finish = item.Finish.Value;
    }
    if (item.Duration != null)
    {
        app.Duration = item.Duration.Value;
    }
}
相关问题