14 Replies - 4287 Views - Last Post: 12 March 2013 - 03:54 PM Rate Topic: -----

#1 OLaceX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 19-April 10

C# XML file search

Posted 07 March 2013 - 02:11 PM

Hi there, I'm a newbie in C# and I'm trying to learn C# using some tutorials and solving some tasks. I have this code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace XML
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlWriter XW = XmlWriter.Create("Student Details.xml");
            XW.WriteStartDocument();

            XW.WriteStartElement("Students");
            //*************************************First subject
            XW.WriteStartElement("Object_Oriented_Programming");

            //*************************************first student
            XW.WriteStartElement("Name");
            XW.WriteString("John");
            XW.WriteEndElement();
            XW.WriteStartElement("Surname");
            XW.WriteString("Doe");
            XW.WriteEndElement();
            XW.WriteStartElement("IndexNo");
            XW.WriteString("10");
            XW.WriteEndElement();
            XW.WriteStartElement("Pass");
            XW.WriteString("Listening");
            XW.WriteEndElement();
            //*************************************second student
            XW.WriteStartElement("Name");
            XW.WriteString("Ted");
            XW.WriteEndElement();
            XW.WriteStartElement("Surname");
            XW.WriteString("Miller");
            XW.WriteEndElement();
            XW.WriteStartElement("IndexNo");
            XW.WriteString("11");
            XW.WriteEndElement();
            XW.WriteStartElement("Pass");
            XW.WriteString("Listening");
            XW.WriteEndElement();
            //*************************************third student
            XW.WriteStartElement("Name");
            XW.WriteString("Jane");
            XW.WriteEndElement();
            XW.WriteStartElement("Surname");
            XW.WriteString("Wolsh");
            XW.WriteEndElement();
            XW.WriteStartElement("IndexNo");
            XW.WriteString("12");
            XW.WriteEndElement();
            XW.WriteStartElement("Pass");
            XW.WriteString("Listening");
            XW.WriteEndElement();
            XW.WriteEndElement();

            //*************************************Second subject
            XW.WriteStartElement("Mathematic");

            //*************************************first student
            XW.WriteStartElement("Name");
            XW.WriteString("John");
            XW.WriteEndElement();
            XW.WriteStartElement("Surname");
            XW.WriteString("Doe");
            XW.WriteEndElement();
            XW.WriteStartElement("IndexNo");
            XW.WriteString("10");
            XW.WriteEndElement();
            XW.WriteStartElement("Pass");
            XW.WriteString("9");
            XW.WriteEndElement();
            //*************************************second student
            XW.WriteStartElement("Name");
            XW.WriteString("Ted");
            XW.WriteEndElement();
            XW.WriteStartElement("Surname");
            XW.WriteString("Miller");
            XW.WriteEndElement();
            XW.WriteStartElement("IndexNo");
            XW.WriteString("11");
            XW.WriteEndElement();
            XW.WriteStartElement("Pass");
            XW.WriteString("9");
            XW.WriteEndElement();
            //*************************************third student
            XW.WriteStartElement("Name");
            XW.WriteString("Jane");
            XW.WriteEndElement();
            XW.WriteStartElement("Surname");
            XW.WriteString("Wolsh");
            XW.WriteEndElement();
            XW.WriteStartElement("IndexNo");
            XW.WriteString("12");
            XW.WriteEndElement();
            XW.WriteStartElement("Pass");
            XW.WriteString("10");
            XW.WriteEndElement();
            XW.WriteEndElement();

            //*************************************Third subject
            XW.WriteStartElement("Data_Bases");

            //*************************************first student
            XW.WriteStartElement("Name");
            XW.WriteString("John");
            XW.WriteEndElement();
            XW.WriteStartElement("Surname");
            XW.WriteString("Doe");
            XW.WriteEndElement();
            XW.WriteStartElement("IndexNo");
            XW.WriteString("10");
            XW.WriteEndElement();
            XW.WriteStartElement("Pass");
            XW.WriteString("8");
            XW.WriteEndElement();

            //*************************************second student
            XW.WriteStartElement("Name");
            XW.WriteString("Ted");
            XW.WriteEndElement();
            XW.WriteStartElement("Surname");
            XW.WriteString("Miller");
            XW.WriteEndElement();
            XW.WriteStartElement("IndexNo");
            XW.WriteString("11");
            XW.WriteEndElement();
            XW.WriteStartElement("Pass");
            XW.WriteString("8");
            XW.WriteEndElement();

            //*************************************third student
            XW.WriteStartElement("Name");
            XW.WriteString("Jane");
            XW.WriteEndElement();
            XW.WriteStartElement("Surname");
            XW.WriteString("Wolsh");
            XW.WriteEndElement();
            XW.WriteStartElement("IndexNo");
            XW.WriteString("12");
            XW.WriteEndElement();
            XW.WriteStartElement("Pass");
            XW.WriteString("10");
            XW.WriteEndElement();
            XW.WriteEndElement();

            XW.WriteEndDocument();
            XW.Close();   
        }
    }
}  



Now, I like to provide a way that you can find a specific student by index and show all the classes for that student on screen. Does any one can show me example how I can do that without using Linq.

Regards

Is This A Good Question/Topic? 0
  • +

Replies To: C# XML file search

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5464
  • View blog
  • Posts: 11,731
  • Joined: 02-June 10

Re: C# XML file search

Posted 07 March 2013 - 02:21 PM

OMG! Talk about brute force.
If this is for OOP then for Pete's sake make a StudentObject class and serialize it.

Objects/classes tutorial linked in my signature block.
Then do this tutorial:
Separating data from GUI - PLUS - serializing the data to XML

Next consider design. You have one file with all of your students? How are you doing to delete one in the middle? Any time you make any change you have to re-write the entire file.

You could make a directory of Students, then write one XML file per student. Now you can hold 125,000 students without having to have the RAM to read them all in as one file. Plus you can move files from subdirectories of StudentsActive to StudentsFailed to StudentsGraduated etc.
Was This Post Helpful? 3
  • +
  • -

#3 OLaceX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 19-April 10

Re: C# XML file search

Posted 07 March 2013 - 03:34 PM

At first thanks for fast answering *tlhIn`toq* . But, this is only a simple exercise, and I work with Console Application so all I like to do here is to search the student and print all classes where this Student exist :). I thinking for some foreach loop, is that possible? I can not find something similar here. I know that this is amateur solution but ... :)
Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5464
  • View blog
  • Posts: 11,731
  • Joined: 02-June 10

Re: C# XML file search

Posted 07 March 2013 - 03:42 PM

A for loop would do it.

Read the document into an array or List<T> of StudentObjects.
Then loop through them looking for whatever parameter you want: Name, ID etc. or just grab one StudentObject out of the List<StudentObject> by index.

This post has been edited by tlhIn`toq: 07 March 2013 - 03:43 PM

Was This Post Helpful? 1
  • +
  • -

#5 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3530
  • View blog
  • Posts: 10,933
  • Joined: 05-May 12

Re: C# XML file search

Posted 07 March 2013 - 05:39 PM

Hmmm... Something caught my eye as being wrong with that XML data format. Running the code, here's the result (after prettifying):
<?xml version="1.0" encoding="utf-8"?>
<Students>
    <Object_Oriented_Programming>
        <Name>John</Name>
        <Surname>Doe</Surname>
        <IndexNo>10</IndexNo>
        <Pass>Listening</Pass>
        <Name>Ted</Name>
        <Surname>Miller</Surname>
        <IndexNo>11</IndexNo>
        <Pass>Listening</Pass>
        <Name>Jane</Name>
        <Surname>Wolsh</Surname>
        <IndexNo>12</IndexNo>
        <Pass>Listening</Pass>
    </Object_Oriented_Programming>
    <Mathematic>
        <Name>John</Name>
        <Surname>Doe</Surname>
        <IndexNo>10</IndexNo>
        <Pass>9</Pass>
        <Name>Ted</Name>
        <Surname>Miller</Surname>
        <IndexNo>11</IndexNo>
        <Pass>9</Pass>
        <Name>Jane</Name>
        <Surname>Wolsh</Surname>
        <IndexNo>12</IndexNo>
        <Pass>10</Pass>
    </Mathematic>
    <Data_Bases>
        <Name>John</Name>
        <Surname>Doe</Surname>
        <IndexNo>10</IndexNo>
        <Pass>8</Pass>
        <Name>Ted</Name>
        <Surname>Miller</Surname>
        <IndexNo>11</IndexNo>
        <Pass>8</Pass>
        <Name>Jane</Name>
        <Surname>Wolsh</Surname>
        <IndexNo>12</IndexNo>
        <Pass>10</Pass>
    </Data_Bases>
</Students>



I think that you should encapsulate the student data within an element.
Was This Post Helpful? 1
  • +
  • -

#6 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3530
  • View blog
  • Posts: 10,933
  • Joined: 05-May 12

Re: C# XML file search

Posted 07 March 2013 - 10:53 PM

Surprisingly this was easy to do without using LINQ. Instead of using LINQ, I wrote what corresponding C# expression would be:
            XDocument doc = Xdocument.Load("Student Details.xml");
            var classes = doc.Descendants("IndexNo")
                             .Where(n => n.Value == "10")
                             .Select(n => n.Parent.Name);

            foreach (var c in classes)
                Console.WriteLine(c);



To me LINQ means "Language INtegrated Query" where there is a query expression that looks like from record_type in repository where conditions select object_builder. In the code above, I'm merely using extension methods.

This post has been edited by Skydiver: 07 March 2013 - 11:02 PM

Was This Post Helpful? 1
  • +
  • -

#7 OLaceX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 19-April 10

Re: C# XML file search

Posted 08 March 2013 - 01:28 AM

* Skydiver * Thank you so much, this code works perfectly as I wanted to do :)/>

Regards

This post has been edited by tlhIn`toq: 08 March 2013 - 07:00 AM

Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5464
  • View blog
  • Posts: 11,731
  • Joined: 02-June 10

Re: C# XML file search

Posted 08 March 2013 - 07:03 AM

That was super nice. But in the future I'd suggest you at least make an effort to code a solution. That's what I was trying to steer you towards. You provided code for writing, but the question was on reading and searching and there was no effort on your part to even try. Commonly that will get a thread bounced to "gimme teh codez".
Was This Post Helpful? 0
  • +
  • -

#9 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3530
  • View blog
  • Posts: 10,933
  • Joined: 05-May 12

Re: C# XML file search

Posted 08 March 2013 - 07:07 AM

Oops! I was under the impression that he had already solved the problem, so I didn't think twice about posting the code above. :( Mea culpa.
Was This Post Helpful? 0
  • +
  • -

#10 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4449
  • View blog
  • Posts: 7,748
  • Joined: 08-June 10

Re: C# XML file search

Posted 08 March 2013 - 01:18 PM

View PostSkydiver, on 07 March 2013 - 11:53 PM, said:

To me LINQ means "Language INtegrated Query" where there is a query expression that looks like from record_type in repository where conditions select object_builder. In the code above, I'm merely using extension methods.


The extension methods defined in the System.Linq assembly? ;)

The query syntax uses the extension methods behind the scenes. It's fair to say that you're using LINQ when you're using the extension methods defined in System.Linq (which I prefer, you actually have more functionality available to you).
Was This Post Helpful? 2
  • +
  • -

#11 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5795
  • View blog
  • Posts: 12,628
  • Joined: 16-October 07

Re: C# XML file search

Posted 09 March 2013 - 05:12 AM

I'm sorry, I'm still trying to get over the horrid XML creation. Such painfully redundant copy paste should make any programmer twitch.

Written slightly more sanely, you see the issue already spotted:
static void WriteStudent(XmlWriter writer, string name, string surname, int indexNo, string pass) {
	writer.WriteElementString("Name", name);
	writer.WriteElementString("Surname", surname);
	writer.WriteElementString("IndexNo", indexNo.ToString());
	writer.WriteElementString("Pass", pass);
}

static void CreateDataFile(string filename) {
	using (var writer = XmlWriter.Create(filename)) {
		writer.WriteStartDocument();
		writer.WriteStartElement("Students");

		writer.WriteStartElement("Object_Oriented_Programming");
		WriteStudent(writer, "John", "Doe", 10, "Listening");
		WriteStudent(writer, "Ted", "Miller", 11, "Listening");
		WriteStudent(writer, "Jane", "Wolsh", 12, "Listening");
		writer.WriteEndElement();

		writer.WriteStartElement("Mathematic");
		WriteStudent(writer, "John", "Doe", 10, "9");
		WriteStudent(writer, "Ted", "Miller", 11, "9");
		WriteStudent(writer, "Jane", "Wolsh", 12, "10");
		writer.WriteEndElement();

		writer.WriteStartElement("Data_Bases");
		WriteStudent(writer, "John", "Doe", 10, "8");
		WriteStudent(writer, "Ted", "Miller", 11, "8");
		WriteStudent(writer, "Jane", "Wolsh", 12, "10");
		writer.WriteEndElement();

		writer.WriteEndElement();
	}
}



Oh, there are so many ways this could be better. Why the hell XML?

And, if it is XML, why not go with it? Quick answer acutally using XML:
var xmlFileName = "Student_Details.xml";
CreateDataFile(xmlFileName);
var doc = new XmlDocument();
doc.Load(xmlFileName);
foreach (XmlNode e in doc.SelectNodes("//*[IndexNo=11]")) {
	Console.WriteLine(e.Name);
}



Of course, if you knew you were going to have to load the whole mess into memory, you should have just built the doc there, rather than dumping to a file.

What tlhIn`toq is talking about, and I agree, is actually using objects you've written for the task:
class Subject {
	public string Name { get; set; }
	public string Pass { get; set; }
}

class Student {
	public string Name { get; set; }
	public string Surname { get; set; }
	public int IndexNo { get; set; }
	public List<Subject> Subjects { get; set; }
}

static List<Student> GetStudents() {
	var list = new List<Student>();
	list.Add(new Student() {
		Name="John", Surname = "Doe", IndexNo = 10, 
		Subjects = new List<Subject>(new Subject[]{
			new Subject{Name = "Object_Oriented_Programming", Pass="Listening"},
			new Subject{Name = "Mathematic", Pass="9"},
			new Subject{Name = "Data_Bases", Pass="8"},
		})
	});
	list.Add(new Student() {
		Name = "Ted", Surname = "Miller", IndexNo = 11,
		Subjects = new List<Subject>(new Subject[]{
			new Subject{Name = "Object_Oriented_Programming", Pass="Listening"},
			new Subject{Name = "Mathematic", Pass="9"},
			new Subject{Name = "Data_Bases", Pass="8"},
		})
	});
	list.Add(new Student() {
		Name = "Jane", Surname = "Wolsh", IndexNo = 12,
		Subjects = new List<Subject>(new Subject[]{
			new Subject{Name = "Object_Oriented_Programming", Pass="Listening"},
			new Subject{Name = "Mathematic", Pass="9"},
			new Subject{Name = "Data_Bases", Pass="8"},
		})
	});

	return list;
}



Getting at the info:
var students = GetStudents();
var found = students.Single((s) => { return s.IndexNo == 11; });
foreach (var sub in found.Subjects) {
	Console.WriteLine(sub.Name + " " + sub.Pass);
}


Was This Post Helpful? 3
  • +
  • -

#12 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3530
  • View blog
  • Posts: 10,933
  • Joined: 05-May 12

Re: C# XML file search

Posted 09 March 2013 - 06:43 AM

View PostCurtis Rutland, on 08 March 2013 - 03:18 PM, said:

View PostSkydiver, on 07 March 2013 - 11:53 PM, said:

To me LINQ means "Language INtegrated Query" where there is a query expression that looks like from record_type in repository where conditions select object_builder. In the code above, I'm merely using extension methods.


The extension methods defined in the System.Linq assembly? ;)/>

The query syntax uses the extension methods behind the scenes. It's fair to say that you're using LINQ when you're using the extension methods defined in System.Linq (which I prefer, you actually have more functionality available to you).


When I was working for the Evil Empire and the idea of LINQ was being floated around, the emphasis was that LINQ was the language extensions that I highlighted above, and not extension methods that implement the standard query operators nor the lambda expressions. But being outside the company, I guess marketing never emphasized that nuance since their goal was to capture mind share away from NHibernate and focus people on the Entities Framework.

Here's an interesting article of how the various bits and pieces came together as what the world outside MS now sees as LINQ: http://msdn.microsof...e/cc163400.aspx
Was This Post Helpful? 1
  • +
  • -

#13 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5795
  • View blog
  • Posts: 12,628
  • Joined: 16-October 07

Re: C# XML file search

Posted 09 March 2013 - 06:58 AM

While I would say I'm not a big fan of LINQ, like Skydiver I do tend to take advantage of all those nice extension methods. I guess I'd say I like LINQ without the LINQ. :P

Curiously, the syntax sugar lambda expression (i) => { return a==42; } seems to be more a compiler bonus. I found this out when recompiling an old .NET 2.0 app and the lambda worked. After all, it's really just delegate(int i) { return i==42; }. I think the var thing actually came in at 2.0?
Was This Post Helpful? 1
  • +
  • -

#14 OLaceX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 19-April 10

Re: C# XML file search

Posted 09 March 2013 - 05:34 PM

Guys, I'm really very grateful, really helped me with these codes. I have no experience with C# so I don't know how much XML is useful, but I just wanted to get introduced with him :). I've read good advices here that I will try to apply it in the future.

Regards to all
Was This Post Helpful? 0
  • +
  • -

#15 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4449
  • View blog
  • Posts: 7,748
  • Joined: 08-June 10

Re: C# XML file search

Posted 12 March 2013 - 03:54 PM

View Postbaavgai, on 09 March 2013 - 07:58 AM, said:

While I would say I'm not a big fan of LINQ, like Skydiver I do tend to take advantage of all those nice extension methods. I guess I'd say I like LINQ without the LINQ. :P/>

Curiously, the syntax sugar lambda expression (i) => { return a==42; } seems to be more a compiler bonus. I found this out when recompiling an old .NET 2.0 app and the lambda worked. After all, it's really just delegate(int i) { return i==42; }. I think the var thing actually came in at 2.0?


var came about in C# 3. But yes, that and many other things (like default and named parameters) are compiler tricks rather than artifacts of framework versions. I've found some of that out the hard way. As long as you're using a more recent compiler, you can use certain new features while targeting frameworks that are older than the features. It's caused me some versioning nightmares, because of the way a method with a parameter with a default value is compiled. I'd have to dig up the code to explain the exact issue, but in any other circumstance the code would have failed to compile. But because the compiler saw the "overload" that matched, it allowed the build. But when the code actually tried to make that method call, there was no method with the appropriate signature.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1