linq到XML-选择XML到一个强大的对象[英] LINQ to XML - selecting XML to a strongly typed object

本文是小编为大家收集整理的关于linq到XML-选择XML到一个强大的对象的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有许多相关问题,但我会将问题分为单独的帖子.

我的XML是<Person>.....<Skills><Skill>Resus<Skill></Skills></Person>

我的代码是:

var products1 = from prd in xDoc.Descendants("Person") 

select new BusinessEntityLayer.Personnel
{
  PayrollNo = (String)prd.Element("PayrollNumber"),
  FirstName = (String)prd.Element("Name"),
  LastName = (String)prd.Element("Surname"),
  StreetAddress = (String)prd.Element("StreetAddress"),
  Suburb = (String)prd.Element("Suburb"),
  HomePhone = (String)prd.Element("HomePhone"),
  MobilePhone = (String)prd.Element("MobilePhone"),
  PagerNumber = (String)prd.Element("PagerNumber"),
  Email = (String)prd.Element("Email"),
  RecordType = (String)prd.Element("RecordType"),
  Skills = (List<String>)prd.Element("Skills")

我的人事课程很强.除了技能收集外,这一切都很好.技能是List<Skill>,但我的代码不会出错 - XLInq.Element to Generic.List ...我也不能使用String[](重构我的商务舱),因为我得到了相同的结果.

人们在这里使用哪些策略?

推荐答案

我认为您应该能够做这样的事情:

Skills = prd.Descendants("Skill").Select(e => new Skill(e.Value)).ToList(),

本文地址:https://www.itbaoku.cn/post/1557030.html

问题描述

I have a number of related issues but I will break the questions down into seperate posts.

My XML is <Person>.....<Skills><Skill>Resus<Skill></Skills></Person>

My code is :

var products1 = from prd in xDoc.Descendants("Person") 

select new BusinessEntityLayer.Personnel
{
  PayrollNo = (String)prd.Element("PayrollNumber"),
  FirstName = (String)prd.Element("Name"),
  LastName = (String)prd.Element("Surname"),
  StreetAddress = (String)prd.Element("StreetAddress"),
  Suburb = (String)prd.Element("Suburb"),
  HomePhone = (String)prd.Element("HomePhone"),
  MobilePhone = (String)prd.Element("MobilePhone"),
  PagerNumber = (String)prd.Element("PagerNumber"),
  Email = (String)prd.Element("Email"),
  RecordType = (String)prd.Element("RecordType"),
  Skills = (List<String>)prd.Element("Skills")

My Personnel class is strongly typed. It all works perfectly apart from the Skills collection. Skills is List<Skill> but my code won't compile with an error - XLInq.Element to Generic.List...nor can I use String[] (refactoring my business class) as I get the same result.

What strategies do people use here?

推荐答案

I think you should be able to do something like this:

Skills = prd.Descendants("Skill").Select(e => new Skill(e.Value)).ToList(),