2012-07-18 5 views
2

뉴스 포털 용 WP 응용 프로그램에서 작업 중입니다. 다양한 피드를 구문 분석해야합니다. 표준 피드는 다음과 같습니다XML Windows Phone에서 Deserialize C#

<feed> 
    <items> 
     <item> 
      ... 
     </item> 
     <item> 
      ... 
     </item> 
    </items> 
</feed> 

나는 그것을 역 직렬화하기 위해이 코드를 사용 :

[XmlRoot("feed")] 
public class News 
{ 
    [XmlArray("items")] 
    [XmlArrayItem("item")] 
    public ObservableCollection<NewsItem> DataSet{ get; set; } 
} 

모든 피드이 잘 작동이 갖는

XDocument document = XDocument.Load(xmlStream); 
XmlSerializer serializer = new XmlSerializer(typeof(News)); 
News MainPage = (News)serializer.Deserialize(document.CreateReader()); 
Dispatcher.BeginInvoke(() => MainPageListBox.ItemsSource = MainPage.DataSet;); 

뉴스 클래스는 다음과 같습니다 하나의 <items> 섹션이있는이 구조체. 그러나 나는 또한 예를 들어, 여러 섹션으로 공급 한 : 나는 위의 C# 코드를 사용하는 경우

<feed> 
    <items section="part 1"> 
     <item> 
      ... 
     </item> 
     <item> 
      ... 
     </item> 
    </items> 
    <items section="part 2"> 
     <item> 
      ... 
     </item> 
     <item> 
      ... 
     </item> 
    </items> 
</feed> 

은 단지 첫 번째 <items> 섹션은 구문 분석, 다른 사람이 무시됩니다. 하나의 XML 피드에 각 <items> 섹션에 대해 별도의 List 또는 ObservableCollection을 만들어야합니다.

아무도 도와 줄 수 있습니까? 고마워.

+0

XML이 클래스의 형식과 일치하지 않습니다 ... 직렬화기를 사용하여 개체를 역 직렬화 할 수 없습니다. –

+0

http://eyeung003.blogspot.com/2010/03/c-net-35-syndication.html –

답변

2

클래스 :/역 직렬화 XML을 직렬화 내

[XmlRoot("feed")] 
    public class News 
    { 
     [XmlArray("items")] 
     public List<NewsItemCollection> DataSet { get; set; } 

     public News() 
     { 
      DataSet = new List<NewsItemCollection>(); 
     } 
    } 

    public class NewsItemCollection 
    { 
     [XmlAttribute("section")] 
     public string Section { get; set; } 

     [XmlElement("item")] 
     public ObservableCollection<NewsItem> Items { get; set; } 

     public NewsItemCollection() 
     { 
      Items = new ObservableCollection<NewsItem>(); 
     } 
    } 

    public class NewsItem 
    { 
     public string Title { get; set; } 
    } 

일부 헬퍼 클래스 :

public static class ObjectExtensions 
    { 
     /// <summary> 
     /// <para>Serializes the specified System.Object and writes the XML document</para> 
     /// <para>to the specified file.</para> 
     /// </summary> 
     /// <typeparam name="T">This item's type</typeparam> 
     /// <param name="item">This item</param> 
     /// <param name="fileName">The file to which you want to write.</param> 
     /// <returns>true if successful, otherwise false.</returns> 
     public static bool XmlSerialize<T>(this T item, string fileName) 
     { 
      return item.XmlSerialize(fileName, true); 
     } 

     /// <summary> 
     /// <para>Serializes the specified System.Object and writes the XML document</para> 
     /// <para>to the specified file.</para> 
     /// </summary> 
     /// <typeparam name="T">This item's type</typeparam> 
     /// <param name="item">This item</param> 
     /// <param name="fileName">The file to which you want to write.</param> 
     /// <param name="removeNamespaces"> 
     ///  <para>Specify whether to remove xml namespaces.</para>para> 
     ///  <para>If your object has any XmlInclude attributes, then set this to false</para> 
     /// </param> 
     /// <returns>true if successful, otherwise false.</returns> 
     public static bool XmlSerialize<T>(this T item, string fileName, bool removeNamespaces) 
     { 
      object locker = new object(); 

      XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(); 
      xmlns.Add(string.Empty, string.Empty); 

      XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); 

      XmlWriterSettings settings = new XmlWriterSettings(); 
      settings.Indent = true; 
      settings.OmitXmlDeclaration = true; 

      lock (locker) 
      { 
       using (XmlWriter writer = XmlWriter.Create(fileName, settings)) 
       { 
        if (removeNamespaces) 
        { 
         xmlSerializer.Serialize(writer, item, xmlns); 
        } 
        else { xmlSerializer.Serialize(writer, item); } 

        writer.Close(); 
       } 
      } 

      return true; 
     } 

     /// <summary> 
     /// Serializes the specified System.Object and returns the serialized XML 
     /// </summary> 
     /// <typeparam name="T">This item's type</typeparam> 
     /// <param name="item">This item</param> 
     /// <returns>Serialized XML for specified System.Object</returns> 
     public static string XmlSerialize<T>(this T item) 
     { 
      return item.XmlSerialize(true); 
     } 

     /// <summary> 
     /// Serializes the specified System.Object and returns the serialized XML 
     /// </summary> 
     /// <typeparam name="T">This item's type</typeparam> 
     /// <param name="item">This item</param> 
     /// <param name="removeNamespaces"> 
     ///  <para>Specify whether to remove xml namespaces.</para>para> 
     ///  <para>If your object has any XmlInclude attributes, then set this to false</para> 
     /// </param> 
     /// <returns>Serialized XML for specified System.Object</returns> 
     public static string XmlSerialize<T>(this T item, bool removeNamespaces) 
     { 
      object locker = new object(); 

      XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(); 
      xmlns.Add(string.Empty, string.Empty); 

      XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); 

      XmlWriterSettings settings = new XmlWriterSettings(); 
      settings.Indent = true; 
      settings.OmitXmlDeclaration = true; 

      lock (locker) 
      { 
       StringBuilder stringBuilder = new StringBuilder(); 
       using (StringWriter stringWriter = new StringWriter(stringBuilder)) 
       { 
        using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings)) 
        { 
         if (removeNamespaces) 
         { 
          xmlSerializer.Serialize(xmlWriter, item, xmlns); 
         } 
         else { xmlSerializer.Serialize(xmlWriter, item); } 

         return stringBuilder.ToString(); 
        } 
       } 
      } 
     } 
    } 

public static class StringExtensions 
    { 
     /// <summary> 
     /// Deserializes the XML data contained by the specified System.String 
     /// </summary> 
     /// <typeparam name="T">The type of System.Object to be deserialized</typeparam> 
     /// <param name="s">The System.String containing XML data</param> 
     /// <returns>The System.Object being deserialized.</returns> 
     public static T XmlDeserialize<T>(this string s) 
     { 
      var locker = new object(); 
      var stringReader = new StringReader(s); 
      var reader = new XmlTextReader(stringReader); 
      try 
      { 
       var xmlSerializer = new XmlSerializer(typeof(T)); 
       lock (locker) 
       { 
        var item = (T)xmlSerializer.Deserialize(reader); 
        reader.Close(); 
        return item; 
       } 
      } 
      catch 
      { 
       return default(T); 
      } 
      finally 
      { 
       reader.Close(); 
      } 
     } 
    } 

테스트 실행 :

News news = new News(); 
      news.DataSet.Add(new NewsItemCollection 
      { 
       Section = "Section1", 
       Items = new ObservableCollection<NewsItem> 
        { 
         new NewsItem { Title = "Test1.1" }, 
         new NewsItem { Title = "Test1.2" } 
        } 
      }); 
      news.DataSet.Add(new NewsItemCollection 
      { 
       Section = "Section2", 
       Items = new ObservableCollection<NewsItem> 
        { 
         new NewsItem { Title = "Test2.1" }, 
         new NewsItem { Title = "Test2.2" } 
        } 
      }); 

      var serialized = news.XmlSerialize(); 
      var deserialized = serialized.XmlDeserialize<News>(); 

재밌게!

+1

왜 '잠금'이 필요합니까? –