Linq to XML查询返回字符串列表

时间:2010-03-15 21:33:59

标签: c# linq linq-to-xml

我有以下课程

public class CountrySpecificPIIEntity
{
    public string Country { get; set; }
    public string CreditCardType { get; set; }
    public String Language { get; set; }
    public List<String> PIIData { get; set; }        
}

我有以下XML,我想使用Linq-to-xml查询并在上面的类中形成

            <?xml version="1.0" encoding="utf-8" ?>
            <piisettings>
              <piifilter country="DE" creditcardype="37" language="ALL" >
                <filters>
                  <filter>FIRSTNAME</filter>
                  <filter>SURNAME</filter>
                  <filter>STREET</filter>
                  <filter>ADDITIONALADDRESSINFO</filter>
                  <filter>ZIP</filter>
                  <filter>CITY</filter>
                  <filter>STATE</filter>
                  <filter>EMAIL</filter>
                </filters>
              </piifilter>
              <piifilter country="DE" creditcardype="37" Language="en" >
                <filters>
                  <filter>EMAIL</filter>
                </filters>
              </piifilter>
            </piisettings>

我正在使用以下查询,但我遇到了最后一个属性,即PIIList。

            var query = from pii in xmlDoc.Descendants("piifilter")
            select new CountrySpecificPIIEntity
            {
               Country = pii.Attribut("country").Value,
               CreditCardType = pii.Attribute("creditcardype").Value,
               Language = pii.Attribute("Language").Value,
               PIIList = (List<string>)pii.Elements("filters")
            };

            foreach (var entity in query)
            {
            Debug.Write(entity.Country);
            Debug.Write(entity.CreditCardType);
            Debug.Write(entity.Language);
            Debug.Write(entity.PIIList);
            }

如何让查询返回要包含在PIIList属性中的List。

2 个答案:

答案 0 :(得分:4)

var query = from pii in xmlDoc.Descendants("piifilter")
select new CountrySpecificPIIEntity
{
   Country = pii.Attribut("country").Value,
   CreditCardType = pii.Attribute("creditcardype").Value,
   Language = pii.Attribute("Language").Value,
   PIIList = pii.Elements("filters").Select(xe => xe.Value).ToList();
};

答案 1 :(得分:0)

我不确定,你能检查一下你的班级定义吗?

public List<String> PIIList { get; set; }

如果这是正确的,那么试试这个:

select new CountrySpecificPIIEntity
{
 Country = pii.Attribute("country").Value,
 CreditCardType = pii.Attribute("creditcardype").Value,
 Language = pii.Attribute("Language").Value,
 PIIList = pii.Elements("filters").Cast<string>().ToList()
}