Solved

Simple problem tahts driving me mad, loading XML

Posted on 2011-03-14
7
236 Views
Last Modified: 2013-12-17
Hi all,

I know this is a very basic problem but I seem to have tried so many ideas im obviously doing something very simple wrong and as I am new to programming (about 5 weeks) I just can't get my head round how to do it.

I have made an app im using as an address book to store contacts, when the program is closed it saves (or generates) an XML file. like the following.

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfContactDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ContactDetails>
    <Name>John Hedges</Name>
    <Mobile>87686767868767</Mobile>
    <Secphone>06785 567787</Secphone>
    <Email>Hedgeart@googlemail.com</Email>
    <Website>http://</Website>
    <Address>64 Flint Hollow Road, Oxford, Ox39 4JT</Address>
    <Notes>Plumber</Notes>
  </ContactDetails>
  <ContactDetails>
    <Name>Dave Parry</Name>
    <Mobile>67877896786867869</Mobile>
    <Secphone />
    <Email>D_Paz@someemail.com</Email>
    <Website>http://</Website>
    <Address />
    <Notes>Drinking Buddy</Notes>
  </ContactDetails>
  <ContactDetails>
    <Name>Shelly</Name>
    <Mobile>07460903356</Mobile>
    <Secphone />
    <Email>Shellby@someemail.com</Email>
    <Website>http://</Website>
    <Address />
    <Notes>G/F</Notes>
  </ContactDetails>
</ArrayOfContactDetails>

Open in new window


ContactDetails is a class and the information is put together as  a List<ContactDetails> contactlist.

All I want to do is when the user reopens the program it loads the XML data and  a Listbox(containing the 'Name' data) is populated, so its exacly how the user leaved it when they exited.

Many Thanks

John


0
Comment
Question by:Bronco78th
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35129699
Looks like you used XML serialization, so to read the file you created:

using System.Text.Xml;
using System.IO;

// Create the XML serializer/de-serializer to read the XML file
// You need to tell the XML serializer what kind of object it's
// going to de-serialize, in this case a List<ContactDetails>
XmlSerializer serializer = new XmlSerializer(typeof(List<ContactDetails>));

// Open the XML file
Stream xmlStream = File.OpenRead("C:\\your.file.xml");
// De-serialize the XML file
List<ContactDetails> contacts = (List<ContactDetails>)serializer.Deserialize(xmlStream);
// Close the XML file
xmlStream.Dispose();

Open in new window

0
 

Author Comment

by:Bronco78th
ID: 35130589
Hi tgerbert

Many thanks for the quick reply, however it seems that hasn't solved the issue, my app is still not picking up that data. Can I just clarify where should I put that deserilisation code?

Heres both the Serilization and Deserlization code that I currently have

Serilization/Writer - - - -

 XmlSerializer writer = new XmlSerializer(typeof(List<ContactDetails>));
                StreamWriter file = new StreamWriter("contactdata.xml");
                writer.Serialize(file, contactlist);
                file.Close(); 

Open in new window


Deserialization (as your code above):-----

     public MainWindow()
        {
            InitializeComponent();

            XmlSerializer serializer = new XmlSerializer(typeof(List<ContactDetails>));
            Stream xmlStream = File.OpenRead("contactdata.xml");
            List<ContactDetails> contacts = (List<ContactDetails>)serializer.Deserialize(xmlStream);
            xmlStream.Dispose();

            UpdatelistNames();

        }

Open in new window


I should have also mentioned in my first post im using WPF and Net 4.0.

Many Thanks

John
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35132688
You should put it where you want to read the XML file.  I would probably put it in it's own method (or even in it's own class).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO;

namespace WpfApplication1
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();

			List<ContactDetails> contacts = ReadContactDetails("C:\\test.xml");

			UpdateListBox(contacts);
		}

		private void UpdateListBox(List<ContactDetails> contacts)
		{
			NamesListBox.Items.Clear();

			foreach (ContactDetails contact in contacts)
				NamesListBox.Items.Add(contact.Name);
		}

		public List<ContactDetails> ReadContactDetails(string PathToXMLFile)
		{
			XmlSerializer deSerializer = new XmlSerializer(typeof(List<ContactDetails>));
			using (Stream xmlStream = File.OpenRead(PathToXMLFile))
				return (List<ContactDetails>)deSerializer.Deserialize(xmlStream);
		}
	}

}

Open in new window


Your code above looks basically correct, though if that's your complete code then it doesn't look like you're doing anything with the List<ContactDetails> that serializer.Deserialize() is giving you - the list is just assigned to the "contacts" variable, and then the method ends.

Since the contacts variable was defined in the MainWindow() method, it's only accessible from within that method and only exists as long as that method is running.  If you want to set a variable in that method, and then be able to use it even after that method has ended, you can declare a class-level variable and use that instead.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO;

namespace WpfApplication1
{
	public partial class MainWindow : Window
	{
		// Class-level variable to hold contacts list
		private List<ContactDetails> contactsList = new List<ContactDetails>();

		public MainWindow()
		{
			InitializeComponent();

			// Fill the contactsList
			contactsList = ReadContactDetails("C:\\test.xml");

			UpdateListBox();
		}

		private void UpdateListBox()
		{
			NamesListBox.Items.Clear();

			// Read contacts from the class-level variable
			foreach (ContactDetails contact in contactsList)
				NamesListBox.Items.Add(contact.Name);
		}

		public List<ContactDetails> ReadContactDetails(string PathToXMLFile)
		{
			XmlSerializer deSerializer = new XmlSerializer(typeof(List<ContactDetails>));
			using (Stream xmlStream = File.OpenRead(PathToXMLFile))
				return (List<ContactDetails>)deSerializer.Deserialize(xmlStream);
		}
	}

}

Open in new window

0
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 

Author Comment

by:Bronco78th
ID: 35133282
rightio ive upped the points value just becuase this is doing my nut as much im sure my incompetance is doing yours...will be well worth the money spent registering here if I can get this sorted.

Anyway its still not showing up. so back to basics....as oviously something is wrong elsewhere. ive stripped out all the code ive got for everything else and stuck in all the releveant bits.

namespace ContactBook
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        [Serializable]
        public class ContactDetails
        {

            public string Name;
            public string Mobile;
            public string Secphone;
            public string Email;
            public string Website;
            public string Address;
            public string Notes;

        }

        List<ContactDetails> contactlist = new List<ContactDetails>();
        private List<ContactDetails> contactsList = new List<ContactDetails>();


        public MainWindow()
        {
            InitializeComponent();

            // Fill the contactsList
            contactsList = ReadContactDetails("C:\\data.xml");

            UpdatelistNames();
        }


        //DESERIALIZER

        public List<ContactDetails> ReadContactDetails(string contactlist)
        {
            XmlSerializer deSerializer = new XmlSerializer(typeof(List<ContactDetails>));
            using (Stream xmlStream = File.OpenRead("data.xml"))
                return (List<ContactDetails>)deSerializer.Deserialize(xmlStream);
        }


        //SAVE CHANGES MESSAGE ON PROGRAM CLOSE + SERILIZATION AND WRITE DATA FILE
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult key = MessageBox.Show(
                "Do you want to Save Changes?",
                "Confirm",
                MessageBoxButton.YesNoCancel,
                MessageBoxImage.Warning,
                MessageBoxResult.No);
            e.Cancel = (key == MessageBoxResult.Cancel);
            if (key == MessageBoxResult.Yes)
            {
                //IM AWARE I HAVE NO ACTURAL CHECKS FOR CHANGES,LOW PRIORITY RIGHT NOW :)

                XmlSerializer writer = new XmlSerializer(contactlist.GetType());
                StreamWriter file = new StreamWriter("data.xml");
                writer.Serialize(file, contactlist);
                file.Close();


            }
        }


        // UPDATES LISTBOX

        private void UpdatelistNames()
        {
            listNames.Items.Clear();

            //Enables/Disables buttons if no items are in the List.
            if (contactlist.Count == 0)
            {
                btnDelete.IsEnabled = false;
                btnCopyfromclipboard.IsEnabled = false;
                btnGentext.IsEnabled = false;
                btnEditcontact.IsEnabled = false;

                menuDeletecontact.IsEnabled = false;
                menuCopycontactclipboard.IsEnabled = false;
                menuEditcontact.IsEnabled = false;
                menuGenTextfile.IsEnabled = false;

            }
            else
            {
                foreach (ContactDetails c in contactlist)
                {
                    listNames.Items.Add(c.Name);
                }

                btnDelete.IsEnabled = true;
                btnCopyfromclipboard.IsEnabled = true;
                btnGentext.IsEnabled = true;
                btnEditcontact.IsEnabled = true;

                menuDeletecontact.IsEnabled = true;
                menuCopycontactclipboard.IsEnabled = true;
                menuEditcontact.IsEnabled = true;
                menuGenTextfile.IsEnabled = true;
            }
        }


        //Compares in the selctions in the listbox
        private void listNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listNames.SelectedIndex != -1)
            {
                String CompareName = listNames.Items[listNames.SelectedIndex].ToString();
                foreach (ContactDetails c in contactlist)
                {
                    if (c.Name == CompareName)
                    {
                        tbName.Text = c.Name;
                        tbMobile.Text = c.Mobile;
                        tbSecphone.Text = c.Secphone;
                        tbEmail.Text = c.Email;
                        tbWebsite.Text = c.Website;
                        tbAddress.Text = c.Address;
                        tbNotes.Text = c.Notes;
                    }
                }
            }
        }

        //BUTTON THAT ADDS NEW CONTACT TO 'contactlist' and listbox
        private void btnCreatecontact_Click(object sender, RoutedEventArgs e)
        {
            String thisName = tbNamefield.Text;
            String thisMobile = tbMobilefield.Text;
            String thisSecphone = tbSecphonefield.Text;
            String thisEmail = tbEmailfield.Text;
            String thisWebsite = tbWebsitefield.Text;
            String thisAddress = tbAddressfield.Text;
            String thisNotes = tbNotesfield.Text;

            if (thisName != "")
            {
                ContactDetails c = new ContactDetails();
                c.Name = thisName;
                c.Mobile = thisMobile;
                c.Secphone = thisSecphone;
                c.Email = thisEmail;
                c.Website = thisWebsite;
                c.Address = thisAddress;
                c.Notes = thisNotes;
                contactlist.Add(c);
                UpdatelistNames();

            }
            else
            {
                MessageBox.Show("You must fill in the Name field");
            }

            tbNamefield.Text = "";
            tbMobilefield.Text = "";
            tbSecphonefield.Text = "";
            tbEmailfield.Text = "";
            tbWebsitefield.Text = "http://";
            tbAddressfield.Text = "";
            tbNotesfield.Text = "";
        }
    }
}
      

Open in new window


Presumably by clicking 'debug' in VS isn't making a difference?...it should still read and ultimatily load the datafile regardless of how I acturally run the program right?

Anyway, sorry to be the thron in your side today.

John
0
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 200 total points
ID: 35139873
I think you just had some confusion between variables.  See comments in the code snippet:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO;

namespace WpfApplication1
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{

		[Serializable]
		public class ContactDetails
		{
			// For sake of testing, I'm just using one property in this object (this is unrelated to your question)
			public string Name;
		}

		//List<ContactDetails> contactlist = new List<ContactDetails>(); <-- seems like a duplicate
		private List<ContactDetails> contactsList = new List<ContactDetails>();
		
		public MainWindow()
		{
			InitializeComponent();

			// Added check for existence of data file
			if (!File.Exists("data.xml"))
				MessageBox.Show("Cannot find data.xml file."); // Really, should just start with blank contacts list/new file in this case

			// Fill the contactsList
			contactsList = ReadContactDetails("data.xml"); // <-- Changed to use same path in Window_Closing

			UpdatelistNames();
		}

		//DESERIALIZER
		public List<ContactDetails> ReadContactDetails(string dataFilePath) // <-- Changed parameter name to dataFilePath
		{
			XmlSerializer deSerializer = new XmlSerializer(typeof(List<ContactDetails>));
			using (Stream xmlStream = File.OpenRead(dataFilePath)) // <-- Changed to use the path passed into this method by contactlist parameter
				return (List<ContactDetails>)deSerializer.Deserialize(xmlStream);
		}

		public void WriteContactDetails(List<ContactDetails> contacts, string dataFilePath) // <-- Added separate method for saving
		{
			XmlSerializer serializer = new XmlSerializer(typeof(List<ContactDetails>));
			Stream dataFileStream = File.Create(dataFilePath);
			serializer.Serialize(dataFileStream, contacts);
			dataFileStream.Dispose();
		}

		//SAVE CHANGES MESSAGE ON PROGRAM CLOSE + SERILIZATION AND WRITE DATA FILE
		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			MessageBoxResult key = MessageBox.Show(
				"Do you want to Save Changes?",
				"Confirm",
				MessageBoxButton.YesNoCancel,
				MessageBoxImage.Warning,
				MessageBoxResult.No);
			e.Cancel = (key == MessageBoxResult.Cancel);
			if (key == MessageBoxResult.Yes)
			{
				//IM AWARE I HAVE NO ACTURAL CHECKS FOR CHANGES,LOW PRIORITY RIGHT NOW :)
				WriteContactDetails(contactsList, "data.xml");
			}
		}

		// UPDATES LISTBOX
		private void UpdatelistNames()
		{
			listNames.Items.Clear();

			foreach (ContactDetails contact in contactsList)
				listNames.Items.Add(contact.Name);

			//Enables/Disables buttons if no items are in the List.
			/* Just for the sake of testing, I've commented out this block
			 * of code so I can run/test the rest of your code without
			 * having to create all these buttons and other controls
			if (contactlist.Count == 0)
			{
				btnDelete.IsEnabled = false;
				btnCopyfromclipboard.IsEnabled = false;
				btnGentext.IsEnabled = false;
				btnEditcontact.IsEnabled = false;

				menuDeletecontact.IsEnabled = false;
				menuCopycontactclipboard.IsEnabled = false;
				menuEditcontact.IsEnabled = false;
				menuGenTextfile.IsEnabled = false;

			}
			else
			{
				foreach (ContactDetails c in contactlist)
				{
					listNames.Items.Add(c.Name);
				}

				btnDelete.IsEnabled = true;
				btnCopyfromclipboard.IsEnabled = true;
				btnGentext.IsEnabled = true;
				btnEditcontact.IsEnabled = true;

				menuDeletecontact.IsEnabled = true;
				menuCopycontactclipboard.IsEnabled = true;
				menuEditcontact.IsEnabled = true;
				menuGenTextfile.IsEnabled = true;
			}*/
		}


		//Compares in the selctions in the listbox
		/* Not related, commented out for testing
		private void listNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (listNames.SelectedIndex != -1)
			{
				String CompareName = listNames.Items[listNames.SelectedIndex].ToString();
				foreach (ContactDetails c in contactlist)
				{
					if (c.Name == CompareName)
					{
						tbName.Text = c.Name;
						tbMobile.Text = c.Mobile;
						tbSecphone.Text = c.Secphone;
						tbEmail.Text = c.Email;
						tbWebsite.Text = c.Website;
						tbAddress.Text = c.Address;
						tbNotes.Text = c.Notes;
					}
				}
			}
		}*/

		//BUTTON THAT ADDS NEW CONTACT TO 'contactlist' and listbox
		/*private void btnCreatecontact_Click(object sender, RoutedEventArgs e)
		{
			String thisName = tbNamefield.Text;
			String thisMobile = tbMobilefield.Text;
			String thisSecphone = tbSecphonefield.Text;
			String thisEmail = tbEmailfield.Text;
			String thisWebsite = tbWebsitefield.Text;
			String thisAddress = tbAddressfield.Text;
			String thisNotes = tbNotesfield.Text;

			if (thisName != "")
			{
				ContactDetails c = new ContactDetails();
				c.Name = thisName;
				c.Mobile = thisMobile;
				c.Secphone = thisSecphone;
				c.Email = thisEmail;
				c.Website = thisWebsite;
				c.Address = thisAddress;
				c.Notes = thisNotes;
				contactlist.Add(c);
				UpdatelistNames();

			}
			else
			{
				MessageBox.Show("You must fill in the Name field");
			}

			tbNamefield.Text = "";
			tbMobilefield.Text = "";
			tbSecphonefield.Text = "";
			tbEmailfield.Text = "";
			tbWebsitefield.Text = "http://";
			tbAddressfield.Text = "";
			tbNotesfield.Text = "";
		}*/
	}

}

Open in new window

0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35139908
>> Presumably by clicking 'debug' in VS isn't making a difference?

Biggest issue there is that VS will compile your .exe, and put it in the "SolutionName\ProjectName\bin\debug" folder and run it from there.  The significance of that is that if you put a data.xml file in "C:\Users\Bronco\Documents\Visual Studio\Projects\SolutionName\" and then click Debug, and your application just specifies "data.xml" without the entire fully qualified path, it's going to look in the current directory for that file, which will be "C:\Users\Bronco\Documents\Visual Studio\Projects\SolutionName\ProjectName\bin\debug\"
0
 

Author Comment

by:Bronco78th
ID: 35140825
Holy moly we got there!!!....that worked!!

Now to apply this new found knowledge to the rest of the program.

Many Thanks sir!

John
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question