-3

as beginner in c# : I googled around but got lost in a "simple question" :

Read a XML : 

    <persons>        this is sample 
      <person id="0">
        <Lname>Johnson</Lname>
        <Fname>Molly</Fname>
      </person>
      <person id="1">
        <Lname>buffalo</Lname>
        <Fname>Mike</Fname>
      </person>
      <person id="2">
        <Lname>COOLS</Lname>
        <Fname>WALTER</Fname>
      </person>
      <person id="3">
        <Lname>FROMUS</Lname>
        <Fname>LUDOVICUS</Fname>
    </persons>

I need to sort on Lname (last name) and Fname (first name)
and list up in a text file (txt) to have

E.G. yo see 2 people have Lname of York so then sort on Fname.

 Case John
 Buffalo Mike
 York Theo
 York Viviane

Lname and Fname should be on same line but take a new line for next Lname , Fname.
thats not in this question because of syntax problems here in this tool (sorry)

Additional info : I tried to use foreach with var instruction to list up but got messed. Target is to use e.g LINQ and OO (object oriented ) as much as possible .

thanks a lot

My response to the comments :


First I want to apologize for the badformed XML -the last tag had a wrong / symbol. The language was indeed dutch (Netherlands) - I changed tag names into english.

What I already have is reading of XML file and sorting on attribute "id" and write into a flat file. Then I tried to make it more OO by exercising the "foreach var constructions using orderedby .

Code I have now :

using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Xml;
using System.Net;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

       XmlReader reader = XmlReader.Create("c:/download/test.xml");

            List<string> Collectperson = new List<string>();
            Collectperson.Clear();

            string personid = "";
            string nm = "";
            string vn = "";
            string oneline = "";
            while (reader.Read())
            {

                if (reader.NodeType != XmlNodeType.EndElement)
                {

                    // Get element name and switch on it.
                    switch (reader.Name)
                    {
                        case "persoon":
                            // Detect this element.
                            // initialize collectperson 
                            Collectperson.Clear();

                            Console.WriteLine(" " + reader.GetAttribute(0));
                            Collectperson.Add(reader.GetAttribute(0));
                            //   add to  file ans reinitialize string 
                            oneline = "";
                            oneline = string.Join(" ", Collectperson.ToArray());

                            break;
                        //
                        case "naam":
                            if (reader.Read())
                            {
                                Console.WriteLine(reader.Value);
                                nm = reader.Value;
                                Collectperson.Add(nm);
                                oneline = string.Join(" ", Collectperson.ToArray());

                            }
                            break;

                        case "voornaam":
                            if (reader.Read())
                            {
                                Console.WriteLine(reader.Value);
                                vn = reader.Value;
                                Collectperson.Add(vn);
                                oneline = string.Join(" ", Collectperson.ToArray());

         // ==================================================================================
                                string path = @"c:/download/personen.txt";
                                // This text is added only once to the file. 
                                if (!File.Exists(path))
                                {
                                    // Create a file to write to. 
                                    using (StreamWriter sw = File.CreateText(path))
                                    {
                                        sw.WriteLine(oneline);
                                    }
                                }

                                // This text is always added, making the file longer over time 
                                // if it is not deleted. 
                                using (StreamWriter sw = File.AppendText(path))
                                {
                                    sw.WriteLine(oneline);
                                }

        //==================================================================================

                            }
                            break;
                    }  // switch
                }
            }  // while 
        }
    }
}
hualpa
  • 1
  • 1
  • 2
    Show us what you've tried and *why* you feel you "got messed." It sounds like you have three questions: how to read xml, how to sort, and how to write to a text file. Have you tried breaking it up? – eddie_cat Sep 12 '14 at 13:40
  • 1
    That xml is not valid. Your ending `personen` tag is not correct, and there is no ending tag for `persoon id="3"`. – gunr2171 Sep 12 '14 at 13:45
  • 1. Punctuation and spelling are a good way to show you put in some effort. 2. Break things up (read xml, sort, write), then look for the answers of the individual questions. These questions have been asked before and are not hard to find – Peter Sep 12 '14 at 13:45

2 Answers2

1

To load xml file into your model, you can use XmlSerializer.Deserialize

using (var sw = new StreamReader(iPathToXMLFile, Encoding.Default))
{
    var ser = new XmlSerializer(typeof(T));
    val = (T)ser.Deserialize(sw);
}

THen, you can create a class for "person" object and then implement IComparable to be able to sort a list of person :) For example : How do I sort an array of custom classes?

[EDIT1]

Another way :

public class Person
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

var list = new List<Person>
{
    new Person {FirstName = "Viviane", LastName = "York"},
    new Person {FirstName = "Mike", LastName = "Buffalo"},
    new Person {FirstName = "Theo", LastName = "York"},
    new Person {FirstName = "John", LastName = "Case"}
};

var sorted = list.OrderBy( p => p.LastName).ThenBy( p => p.FirstName).ToList();

[EDIT2] : IComparable solution

public class Person : IComparable<Person>
{
    public String FirstName { get; set; }
    public String LastName { get; set; }

    public int CompareTo(Person obj)
    {
        var val = String.Compare(LastName, obj.LastName, StringComparison.Ordinal);

        // Same LastName case
        if (0 == val)
            val = String.Compare(FirstName, obj.FirstName, StringComparison.Ordinal);

        return val;
    }
}

        var list = new List<Person>
        {
             new Person {FirstName = "Viviane", LastName = "York"},
            new Person {FirstName = "Mike", LastName = "Buffalo"},
            new Person {FirstName = "Theo", LastName = "York"},
            new Person {FirstName = "John", LastName = "Case"}
        };


        list.Sort(); // Sort will call IComparable implementation of the Person class

[EDIT3]

You can also use IComparer, delegates... I let you search the web for this.

Community
  • 1
  • 1
Hellin
  • 62
  • 8
0

This video may help you out. He explains using XML first and then Json. I prefer Json, and you might also after watching this. Bob Tabor explains things very well. Hope this steers you on the right track.

<<Storing and retrieving Serialized Data>>

Justin Markwell
  • 341
  • 6
  • 13