seralize object returns empty file after save

Kran2022 381 Reputation points
2023-01-26T12:46:59.28+00:00

Hello All, Morning:

I'm reading a XML file to fill the datagrid have no issues; then i modify the some values in the datagrid then save back to the xml file without changing the structure of the file. When i tried to seralize the file, empty file is saved i.e. no contents in the file.

During debug i could see the productpricelist list contains all the data but saved file is empty.

Could you please tell me what is the issue here? thanks for your help?




    class ProductPriceViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public ICommand MyCommand { get => new RelayCommand(executemethod, canexecutemethod); }
        private static bool canexecutemethod(object obj) => true;

      
        public void OnPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }


        public ProductPriceViewModel()
        {
            ProductPriceList = new ObservableCollection<Products>(GetProductsPriceList());
            this.View = new ListCollectionView(this.productpricelist);       
            this.View.Filter = Filter;
            command = new RelayCommand(Execute);
        }

        public ObservableCollection<Products> Items { get; set; }

        private readonly ICommand command;
        public ICommand Command
        {
            get{return command;  }
        }
     

        private ObservableCollection<Products> productpricelist;

        public ObservableCollection<Products> ProductPriceList
        {
            get { return productpricelist; }
            set
            {
                productpricelist = value;
                OnPropertyChanged("ProductPriceList");
            }
        }
    

        private ICollectionView cvs;
        public ICollectionView View
        {

            get { return cvs; }
            set
            {
                cvs = value;
                OnPropertyChanged("View");
            }
        }



        private void Execute(object parm) //serialize to file
        {

            var serializer = new XmlSerializer(typeof(Products));
            using (var writer = new XmlTextWriter(@"C:\xmltest\Dta.txt", Encoding.UTF8))
            {
                serializer.Serialize(writer, productpricelist);
            }
           
        }

       
       private ObservableCollection<Products> GetProductsPriceList() //to read xml fiel contents 
        {

            var mylist = new ObservableCollection<Products>();
            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:\xmltest\26112023.txt");
            foreach (XmlElement pn in doc.SelectNodes("/Data/Products/*"))
            {
                var productlist = new Products
                {
                    Mainproduct = pn.LocalName.ToString(),
                    Name = pn.GetAttribute("Name"),
                    Price = pn.SelectSingleNode(".//ProductPrice/@Price")?.Value,
                    Visible = pn.SelectSingleNode(".//ProductVisibility/@Visible")?.Value,
                    NameIcon = pn.GetAttribute("DefaultIconName")
                };
                mylist.Add(productlist);
            }

            return mylist;
        }
      
    }

    public class Products
    {

        string mainproduct;
        string name;
        string price;
        string visible;
        string nameicon;

        public string Mainproduct
        {
            get { return mainproduct; }
            set { mainproduct = value; }
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public string Price
        {
            get { return price; }
            set { price = value; }
        }
        public string Visible
        {
            get { return visible; }
            set { visible = value; }
        }
        public string NameIcon
        {
            get { return nameicon; }
            set { nameicon = value; }
        }
    }

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,667 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,204 questions
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,231 Reputation points
    2023-01-26T15:39:52.87+00:00

    Hi,
    you can simplified your code. If you serialize with XmlSerializer you can use XmlSerializer to deserialize: (whole demo: x.txt)

    #pragma warning disable CS8601 // Dereference of a possibly null reference.
    #pragma warning disable CS8602 // Dereference of a possibly null reference.
    		private void SaveProductsPriceList() //to read xml fiel contents 
    		{
    			var serializer = new XmlSerializer(typeof(ObservableCollection<Products>));
    			using (var writer = new XmlTextWriter(FilePath, Encoding.UTF8))
    				serializer.Serialize(writer, ProductPriceList);
    		}
    
    #pragma warning disable CS8603 // Possible null reference return.
    		private ObservableCollection<Products> GetProductsPriceList() //to read xml fiel contents 
    		{
    			var serializer = new XmlSerializer(typeof(ObservableCollection<Products>));
    			using (Stream str = new FileStream(FilePath, FileMode.Open))
    				return (ObservableCollection<Products>)serializer.Deserialize(str);
    
    			// old wrong version 
    
    			//var mylist = new ObservableCollection<Products>();
    			//XmlDocument doc = new XmlDocument();
    			//doc.Load(FilePath);
    			//foreach (XmlElement pn in doc.SelectNodes("/Products"))
    			//{
    			//	var productlist = new Products
    			//	{
    			//		Mainproduct = pn.LocalName.ToString(),
    			//		Name = pn.GetAttribute("Name"),
    			//		Price = pn.SelectSingleNode(".//ProductPrice/@Price")?.Value,
    			//		Visible = pn.SelectSingleNode(".//ProductVisibility/@Visible")?.Value,
    			//		NameIcon = pn.GetAttribute("DefaultIconName")
    			//	};
    			//	mylist.Add(productlist);
    			//}
    			//return mylist;
    		}
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful