2016-11-13 3 views
3

내 LINQ 내가 다음과 같은 클래스의 목록에 쿼리의 결과를 변환 할 수있는 방법 XNode를 사용자 정의 유형으로 변환하려면 어떻게해야합니까? XML 쿼리에

<entry> 
    <key>keyName</key> 
    <value>valueName</value> 
</entry> 

의 목록을 반환

XDocument xdoc = XDocument.Load("test.xml"); 
IEnumerable<XNode> lv1s = from lv1 in xdoc.Descendants("resources") select lv1.FirstNode; 

입니까?

/// <remarks/> 
    [System.SerializableAttribute()] 
    [System.ComponentModel.DesignerCategoryAttribute("code")] 
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] 
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] 
    public partial class entry 
    { 

     private string keyField; 

     private string valueField; 

     /// <remarks/> 
     public string key 
     { 
      get 
      { 
       return this.keyField; 
      } 
      set 
      { 
       this.keyField = value; 
      } 
     } 

     /// <remarks/> 
     public string value 
     { 
      get 
      { 
       return this.valueField; 
      } 
      set 
      { 
       this.valueField = value; 
      } 
     } 
    } 

답변

1

합니다. 당신이 요소가없는 당신의 XML 트리, 예를 들어,의 노드를 건너 뛸 수 있습니다 OfType<T>를 사용하여 XElement

var converted = lv1s.OfType<XElement>().Select(lv1 => new entry { 
    key = lv1.Element("key").Value 
, value = lv1.Element("value").Value 
}); 

필터링 XNode 아래 S : 당신이 원하는 타입의 객체를 생성 new를 사용할 필요가 있도록, 그들을 캐스팅 할 수 없습니다 코멘트.

3

당신은 XElement 대신 XNode과 함께 일할 수있는 다음과 같은 것을 할 수 있습니다 : XML의 요소를 나타내는, 당신이 얻을 요소 유형 XNode의이다

IEnumerable<entry> lv1s = from lv1 in xdoc.Descendants("resources") 
          select new entry { 
            key = lv1.Element("key").Value, 
            value = lv1.Element("value").Value 
          }; 
+0

컬렉션을 목록으로 필요로하는 경우 끝에'.ToList()'를 슬링 할 수 있습니다. – Braydie