0

我有以下 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" />

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

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

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

2 回答 2

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

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

于 2012-06-19T19:48:49.797 回答
1
var r = from d in doc.Elements("data")
        let name = (string)d.Attribute("name")
        select name;
于 2012-06-19T20:07:33.640 回答