Thread: Reading an XML file

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    903

    Reading an XML file

    Hey guys. I just started learning C# and I wanted to do an application to manage books (which book for which course and its cost, etc) and evaluation notes for each course as well (including some neat features I just thought of) and well I thought that for saving/loading files I could use an XML document for each user since I know C# has built-in support for XML reading. Ok so I've tried creating an object of XmlReader and it says it cannot be instanciated so I tried this and it just doesn't output anything at all. What's wrong ? Basically with this code I wanted to output everything in the file just to know if I was able to but what I want to read is a file formatted like this:

    Code:
    <root>
      <course="Math">
        <book>
          <author>
            am&#233;lie nothomb
          </author>
          <title>
            m&#233;taphysique des tubes
          </title>
          <isbn>
          </isbn>
          <price>
            10.45
          </price>
        </book>
        <evaluation>
          <title>
            recherche
          </title>
          <note>
            70.3
          </note>
          <max>
            100.0
          </max>
          <group>
            65.4
          </group>
          <weight>
            20
          </weight>
        </evaluation>
      </course>
    </root>
    Code:
    using System;
    using System.IO;
    using System.Xml;
    
    class MyApp
    {
    	public static void Main()
    	{
    		FileStream fs = new FileStream("test.xml", FileMode.Open);
    		XmlReader xml_reader = new XmlTextReader(fs);
    		while(!xml_reader.EOF) Console.WriteLine(xml_reader.ReadString());
    		Console.Read();
    	}
    }
    Any idea/suggestion/comment is welcome and feel free to ask me any question if my question isn't too clear as I haven't built up vocabulary for C# yet. (I don't know the exact words).

    Edit: It seems like the application isn't doing anything yet the only way to close the program is through CTRL + C.

  2. #2
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    I can answer this two different ways. First, the helpful answer:
    Quote Originally Posted by Desolation
    I thought that for saving/loading files I could use an XML document for each user since I know C# has built-in support for XML reading.
    Do you want to write the loading and saving code, or do you want C# to do it for you? If you don't mind C# doing the work, you can write a class that encapsulates all your data and mark it as Serializable. Is it important that the file is in XML? If not, you can use a BinaryFormatter. If so, you can use a SoapFormatter.
    Code:
    [Serializable]
    class Test
    {
    	public string _name;
    	public int _number;
    	public double _price;
    
    	public void Print()
    	{
    		Console.WriteLine("Name: {0}", _name);
    		Console.WriteLine("Number: {0}", _number);
    		Console.WriteLine("Price: {0}", _price);
    	}
    }
    
    class Program
    {
    static void Main(string[] args)
    {
    	Test test = new Test();
    	test._name = "My name";
    	test._number = 42;
    	test._price = 3.141592;
    
    	Console.WriteLine("Before serialization the object contains: ");
    	test.Print();
    
    	//SoapFormatter formatter;
    	BinaryFormatter formatter;
    
    	//Opens a file and serializes the object into it in binary format.
    	using (Stream stream = File.Open("data.bin", FileMode.Create))
    	{
    		//formatter = new SoapFormatter();
    		formatter = new BinaryFormatter();
    
    		formatter.Serialize(stream, test);
    	}
    
    	//Empties obj.
    	test = null;
    
    	//Opens file "data.xml" and deserializes the object from it.
    	using (Stream stream = File.Open("data.bin", FileMode.Open))
    	{
    		//formatter = new SoapFormatter();
    		formatter = new BinaryFormatter();
    
    		test = (Test)formatter.Deserialize(stream);
    	}
    
    	Console.WriteLine();
    	Console.WriteLine("After deserialization the object contains: ");
    	test.Print();
    
    	Console.WriteLine("Finished");
    	Console.ReadLine();
    }
    }
    Now, the second part. Notice those using statements up there? It's good practice to use 'em on every local object that implements IDisposable. For example, your code could be:
    Code:
    using (FileStream fs = new FileStream("test.xml", FileMode.Open))
    {
    	using (XmlReader xml_reader = new XmlTextReader(fs))
    	{
    		while (!xml_reader.EOF)
    			Console.WriteLine(xml_reader.ReadString());
    	}
    
    }
    Console.Read();
    Why are the using statements important? Because they ensure that Dispose() will be called no matter how you leave that scope block. Calling Dispose is a good thing because it avoid the performance penalites of running finalizers. However, I really don't know how to use the XmlReader to actually read that document. Good luck doing that if that's really what you need to do.

    [edit] Sorry for all the text, but I figured I'd better make my 1,000th post worth something.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    903
    Ok well, here's how I've structured my code up to now. I know it may be not top-notch C# code but it does the job. (I've stripped a lot of it so that it is shorter and to-the-point).
    Code:
    /*
     * Created by SharpDevelop.
     * User: Alexandre
     * Date: 2006-08-15
     * Time: 15:17
     * 
     * To change this template use Tools | Options | Coding | Edit Standard Headers.
     */
    
    using System;
    using System.Collections.Generic;
    
    namespace StudentData
    {
    	class Book
    	{
    		public String Title, ISBN, Author;
    		public float Price;
    	}
    	
    	class Evaluation
    	{	
    		public String Name;
    		public float Note, MaxScore, GroupAvg, Weight;
    	}
    
    	class Course
    	{
    		public void AddBook(Book b)
    		{
    			BookList.Add(b);
    		}
    		
    		public void AddBook(String t, String a, String i, float p)
    		{
    			BookList.Add(new Book(t, a, i, p));
    		}
    		
    		public void AddEvaluation(Evaluation ev)
    		{
    			EvaluationList.Add(ev);
    		}
    		
    		public void AddEvaluation(String na, float no, float m, float g, float w)
    		{
    			EvaluationList.Add(new Evaluation(na, no, m, g, w));
    		}
    
    		private String Name, Id;
    		private List<Evaluation> EvaluationList;
    		private List<Book> BookList;
    	}
    	
    	class StudentManager
    	{
    		public void GetDataFromFile(String file_name)
    		{
    			// This is where I want to read the file
    
    		}
    		
    		private List<Course> CourseList;
    	}
    }
    Basically I don't really need it to be of any specific format at all, I just need to write the file so that I can read from it and write to it easily.

    Thanks =]

  4. #4
    and the Hat of Clumsiness GanglyLamb's Avatar
    Join Date
    Oct 2002
    Location
    between photons and phonons
    Posts
    1,110
    However, I really don't know how to use the XmlReader to actually read that document. Good luck doing that if that's really what you need to do.
    I have not fiddled with it too much but basically you'll create a class that has this [Serializeble] thing ( in this case the class will be root ). Next you have for every field a property ( getter ). Also above each field you can again specify some xml characteristics using the [ and ].

    Thats how its supposed to be, although like I said I've never attempted to do this. I've only used the xmlSerializer to serialize objects, write them to files to later deserialize them. But still you can try it, and create an object, serialize, check output and start funetuning, but maybe you'r better of writing your own serializer in the end , since development time could be less.

  5. #5
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Actually, making use of the normal .Net serialization is a cinch. In the OP's case, all he has to do is mark all of his classes as Serializable. To save data to the file, make a formatter and call Serialize with the CourseList as the argument. To load data from the file, make a formatter and call Deserialize, casting and assigning CourseList from the return type. The nice thing about normal serialization is that you don't have to have public getters for all the things you want to save; normal serialization serializes everything, including private stuff.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  6. #6
    Registered User
    Join Date
    May 2006
    Posts
    903
    Thanks a lot guys ! This way I can make modifications to the class objects on runtime and then erase the old file and put the new content in ! Thank you guys so much =]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM