仅选择父元素的属性

时间:2012-06-19 19:46:23

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

我有以下XML:

<data name="zzz_AbsenceReportDR" time="2012-06-19 13:36:40Z" xmlns="">
    <row conf="88945498" date="6/19/2012" employee_identifier="mickeymouse" school_name="City Academy" substitute_identifier="" start_time_absence="7:15:00 AM" end_time_absence="3:00:00 PM" filled="No" school_external_id="309" school_dbkey="83235" notes_to_administrator="My lesson plans are in my mailbox." notes_only_for_administrators="" last_update="6/18/2012 6:00:24 PM" notes="We have PE on Monday." last_approval_action="" created="6/18/2012" cancelled="No" absence_last_update="6/18/2012 6:00:24 PM" absence_reason="Personal" approval_status="Unapproved" approved_by="" needs_approval="Yes" />
    <row conf="88946034" date="6/19/2012" employee_identifier="AntwanTeacher" school_name="College Academy" substitute_identifier="" start_time_absence="7:30:00 AM" end_time_absence="3:30:00 PM" filled="No" school_external_id="213" school_dbkey="83244" notes_to_administrator="" notes_only_for_administrators="" last_update="6/18/2012 7:00:24 PM" notes="Lesson Plan on Desk" last_approval_action="" created="6/18/2012" cancelled="No" absence_last_update="6/18/2012 7:00:24 PM" absence_reason="Personal" approval_status="Unapproved"approved_by="" needs_approval="Yes" />
    <row conf="88946035" date="6/19/2012" employee_identifier="vinnieteacherman" school_name="Oakland Academy" substitute_identifier="" start_time_absence="7:35:00 AM" end_time_absence="3:10:00 PM"filled="No" school_external_id="207" school_dbkey="83242" notes_to_administrator="" notes_only_for_administrators="" last_update="6/18/2012 7:00:24 PM" notes="" last_approval_action="" created="6/18/2012" cancelled="No" absence_last_update="6/18/2012 7:00:24 PM" absence_reason="Personal" approval_status="Unapproved" approved_by="" needs_approval="Yes" />

行是动态生成的(并且在将来的某个时间点)可能具有名为&#34; name&#34;的属性。什么是LINQ表达式,仅从数据(父)元素中选择name属性的值?我使用下面的代码,但我担心它还会返回名为&#34; name&#34;的行属性。

var xElems = from x in xmlDoc.Descendants()
             where x.Name.LocalName == "data"
             select x;

foreach (var xElem in xElems)
{
    Console.WriteLine(xElem.Attribute("name"));
}

2 个答案:

答案 0 :(得分:1)

var elems = xmlDoc.Descendants("data")
                  .Select(e => (string)e.Attribute("name"))
                  .ToList();

如果只有data元素始终位于文件结构的顶部,则可以将Descendants替换为Elements

答案 1 :(得分:1)

var r = from d in doc.Elements("data")
        let name = (string)d.Attribute("name")
        select name;