如何从xml通过linq获取所有“属性”到xml

XML示例( 原始链接 ):

  Sven infinity2 12/15/2009   Josephine infinity3 01/02/2010   Frankie wk-infinity9 10/02/2009   

我想在xml中为每个记录获取一个类的实例。

我在这里找到了类似的例子,但他们只有一个根,然后有一个元素深。 它工作,直到我把其他元素放入。我希望能够做类似的事情

 foreach(Record rec in myVar) { Console.WriteLine("ID: {0} User:{1} Domain:{2} LastLogon:{3}",rec.Index, rec.Username, rec.Domain, rec.LastLogon); } 

编辑:使用ToDictionary方法更新代码,以ToDictionary清晰度和效率。

您可以尝试以下示例。 如果从select new Record行中删除Record ,它将产生匿名类型并仍然有效。 如果已经提供了其他构造函数,则Record类应该有一个默认的无参数构造函数来使用对象初始化程序(如果没有构造函数,它也可以工作)。 否则,您可以使用可用的构造函数而不是对象初始值设定项。

请注意,使用Single()Value假定XML格式正确,没有任何缺少的元素。

 var xml = XElement.Parse(@"  Sven infinity2 12/15/2009   Josephine infinity3 01/02/2010   Frankie wk-infinity9 10/02/2009  "); var query = from record in xml.Elements("record") let properties = record.Elements("property") .ToDictionary(p => p.Attribute("name").Value, p => p.Value) select new Record { Index = record.Attribute("index").Value, Username = properties["Username"], Domain = properties["Domain"], LastLogon = properties["LastLogon"] }; foreach(var rec in query) { Console.WriteLine("ID: {0} User:{1} Domain:{2} LastLogon:{3}", rec.Index, rec.Username, rec.Domain, rec.LastLogon); } 

编辑:我已经使用更ToDictionary ,更快速的ToDictionary方法更新了上面的代码示例。 根据我的基准测试工作,最快的是ToDictionary ,其次是Func ,然后是Where方法。

原始查询

 var query = from record in xml.Elements("record") let properties = record.Elements("property") select new Record { Index = record.Attribute("index").Value, Username = properties.Where(p => p.Attribute("name").Value == "Username").Single().Value, Domain = properties.Where(p => p.Attribute("name").Value == "Domain").Single().Value, LastLogon = properties.Where(p => p.Attribute("name").Value == "LastLogon").Single().Value }; 

用Func查询

使用以下代码可以减少原始查询的冗余:

 Func GetAttribute = (e, property) => e.Elements("property") .Where(p => p.Attribute("name").Value == property) .Single().Value; var query = from record in xml.Elements("record") select new Record { Index = record.Attribute("index").Value, Username = GetAttribute(record, "Username"), Domain = GetAttribute(record, "Domain"), LastLogon = GetAttribute(record, "LastLogon") };