Sunday, 23 October 2016

c# xdocument

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace XDocumentDemo
{
    public partial class Form1 : Form
    {
        CustomerManager Manager { get; set; }

        public Form1()
        {
            InitializeComponent();

            //populate the combobox
            Manager = new CustomerManager();
            uxCountries.DataSource = Manager.GetCountries();
        }

        private void uxCountries_SelectedIndexChanged(object sender, EventArgs e)
        {
            var name = uxCountries.SelectedItem.ToString();

            uxCustomers.DataSource = Manager.GetCustomersByCountry(name);
        }
    }
}

---------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq; //for XDocument class
using System.Collections;

namespace XDocumentDemo
{
    public class CustomerManager
    {
        XDocument Document { get; set; }

        public CustomerManager()
        {
            Document = XDocument.Load("nw_customers.xml");
        }

        public IList<string> GetCountries()
        {
            var countries = Document.Descendants("Country").OrderBy(c => c.Value).
                            Select(c => c.Value).Distinct().ToList();
            return countries;
        }

        public IList GetCustomersByCountry(string country)
        {
            var customers =
                from cust in Document.Descendants("Customers")
                where cust.Element("FullAddress").Element("Country").Value == country
                select new
                {
                    Company = cust.Element("CompanyName").Value,
                    Contact = cust.Element("ContactName").Value,
                    Phone = cust.Element("Phone").Value,
                    City = cust.Element("FullAddress").Element("City").Value
                };
            return customers.ToList();
        }
       
    }
}

No comments:

Post a Comment