XML Data Binding in Windows Phone/Store Applications

This article describes about the Binding of XML data to a control in Windows Phone application. XML data binding will be achieved in three steps as below.

i) Read the content from XML document
ii) Convert the content to JSON response
iii) De serializes the JSON response to entity of object which will be used as binding property.

You can refer the same code to implement this XML data binding mechanism in Windows Store apps.

Read the Content from XML Document:
1) Create a windows Phone project in MVVM light, add the XML document to Assets folder and set the properties, Build Action to Embedded Resource and Copy to Output directory to ā€œCopy Alwaysā€.

<?xml version="1.0" encoding="utf-8" ?>
<NewsItems>
  <NewsItem>
    <Title>Gulf Work Schedule</Title>
    <Description>
      Designed to you and your customers quick access to the last schedule of all premier workshops

      The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
    </Description>
  </NewsItem>
  <NewsItem>
    <Title>Gulf Service Catalog</Title>
    <Description>
      This App is designed to provide you quick access to zoom in to the relevant service offerings.

      Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

      The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
    </Description>
  </NewsItem>
  <NewsItem>
    <Title>Standard Bank</Title>
    <Description>Learn about Standard Bank by Microsoft Services and download it from the company portal</Description>
  </NewsItem>
</NewsItems>

2) Read XML document as stream

  private async Task<Stream> ReadFileAsync(string fileName)
        {
            var file = await StorageFile.GetFileFromPathAsync(fileName);

            return await file.OpenStreamForReadAsync();
        }

3) Use Stream Reader to read the Stream object

private async Task<StreamReader> GetFileContents(string fileName)
        {
            var stream = await this.ReadFileAsync(Path.Combine(Path.Combine(Package.Current.InstalledLocation.Path, "Assets"), "Main.xml"));
            return new StreamReader(stream);
        }

Convert the content to JSON response:

1) Parse and serialize the Stream Reader content to JSON Response

private string GetJsonFormattedData(StreamReader streamReader)
        {
            if (streamReader == null)
            {
                return string.Empty;
            }


            var xmlContent = streamReader.ReadToEnd();
            var document = XDocument.Parse(xmlContent);
            return JsonConvert.SerializeXNode(document);
         }

De serializes the JSON response to entity of object which will be used as binding property:

1) Create a Model class and define the properties
2) Make sure your model class has to be serialized before De serializing JSON response to this class type. For this, you just need to add the DataContract attribute at class level and DataMember attribute at properties level.

[DataContract]
    public class NewsItem
    {
        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        [DataMember]
        public string Title { get; set; }

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        [DataMember]
        public string Description { get; set; }
    }

3) Add extension method to desterilize the Json response.

public static T Deserialize<T>(this string json)
        {
            T returnValue = default(T);
            try
            {
                if (!string.IsNullOrEmpty(json))
                {
                    using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
                    {
                        var serializer = new DataContractJsonSerializer(typeof(T));
                        returnValue = (T)serializer.ReadObject(stream);
                    }
                }
            }
            catch (InvalidOperationException)
            {
                returnValue = default(T);
            }
            catch (ArgumentOutOfRangeException)
            {
                returnValue = default(T);
            }
            catch (ArgumentException)
            {
                returnValue = default(T);
            }

            return returnValue;
        }

4) Now de serialize the JSON response to a model class type

var newsItems = newsItemsJson.Deserialize<NewsItems>();

5) Use the model class as Binding property in MainViewModel.cs file

public List<NewsItem> News
        {
            get
            {
                return this.news;
            }

            set
            {
                this.news = value;
                this.RaisePropertyChanged(() => this.News);
            }
        }

        private async Task LoadData()
        {
            this.News = await this.dataService.GetLatestNews();
        }

6) Now add the control in MainPage.XAML and Bind the Viewmodel property.

<phone:LongListSelector ItemsSource="{Binding News}" LayoutMode="List" />

Press F5 to run the app.

Download the source code from below location
http://nullskull.com/FileUpload/-407123783_XMLDataBinding.zip  


By Siva Jagan Dhulipalla   Popularity  (3367 Views)