tags:

views:

438

answers:

5

ok, so i have a text file system worked out. but its a mess, and i want to organize it.. so here is an example of what i have saved in my file.txt

feild1 feild2 feild3 feild4
myname myhashedpass [email protected] more stuf
etc etc etc etc

so, each line is converted into four strings, string Name; string Pass; string Email; string Host; .... then stored in an object.

i want to get my text file (see above) to an xml file, like this:

<person1>
   <name>myname</name>
   <pass>myhashedpass</pass>
   <email>etc</email>
</person1>

<person2>
etc etc etc etc

basically, i need to know how to store, from four strings, TO an xml file.. correctly.. and then how to use something like:

foreach person
   foreach string in person
      get all the parts of person, and put them in the correct of four strings so that i can use them in my program

ive looked up tuts around, but i cant seem to find what im looking for. im looking for code examples if possible.. thanks in advance!

+1  A: 

You may want to take a look at this XML Serialization tutorial. Serialization can save you a lot of work loading and saving the XML file.

jasonh
+1  A: 

Linq provides a nice way to construct XML using the XNodes:

from p in person
  select new XElement("person",
    from s in p.Keys
      select new XElement(s, p[s]));

Easy as cake.

John Gietzen
+1  A: 

It's not exactly clear from your question, but it sounds like you are serializing a Person class to a text file. This is probably the perfect use case for the XmlSerializer.

Example code:

class Person
{
    // XmlSerializer requires parameterless constructor
    public Person()
    {
    }

    public string Name { get; set; }

    public string Pass { get; set; }

    public string Email { get; set; }

    public string Host { get; set; }
}

// ...

XmlSerializer serializer = new XmlSerializer(typeof(Person));

// Write a person to an XML file
Person person = new Person() { Name = "N", Pass = "P", Email = "E", Host = "H" };
using (XmlWriter writer = XmlWriter.Create("person.xml"))
{
    serializer.Serialize(writer);
}

// Read a person from an XML file
using (XmlReader reader = XmlReader.Create("person.xml"))
{
    person = (Person)serializer.Deserialize(reader);
}
bobbymcr
The changing element names (a bad idea) make this tricky
Marc Gravell
I suppose. Well, hopefully that will be resolved when the OP moves to a standard serialization mechanism!
bobbymcr
+3  A: 

so to read out your original file, you have something like:

var people = File.ReadAllLines("filename"))
    .Select(line => { 
       var parts = line.Split();
       return new Person { 
           Name = parts[0],
           Password = parts[1],
           Email = parts[2]
       });

then you can write out to xml by:

var serializer = new XmlSerializer(typeof(Person));
var xmlfile = File.OpenWrite("somefile");
foreach(var person in people)
    serializer.Serialize(person, xmlfile);
Jimmy
Doesn't *exactly* answer the OP's question as it won't write the exact XML format specified, but +1 for nice nice of LINQ on the reader!
Marc
+1  A: 

The litteral answer to your question is this:

using System;
using System.Linq;
using System.Xml.Linq;

namespace XmlSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            var person1 = new Person();
            person1.Name = "Joe";
            person1.Password = "Cla$$ified";
            person1.Email = "[email protected]";

            var person2 = new Person();
            person2.Name = "Doe";
            person2.Name = "$ecret";
            person2.Email = "[email protected]";

            var persons = new[] {person1, person2};

            XElement xml = new XElement("persons",
                                        from person in persons
                                        select new XElement("person",
                                                            new XElement("name", person.Name),
                                                            new XElement("password", person.Password),
                                                            new XElement("email", person.Email))
                                        );
            xml.Save("persons.xml");

            XElement restored_xml = XElement.Load("persons.xml");
            Person[] restored_persons = (from person in restored_xml.Elements("person")
                                         select new Person
                                                    {
                                                        Name = (string)person.Element("name"),
                                                        Password = (string)person.Element("password"),
                                                        Email = (string)person.Element("email")
                                                    })
                                        .ToArray();
            foreach (var person in restored_persons)
            {
                Console.WriteLine(person.ToString());
            }
            Console.ReadLine();
    }
}

public class Person
{
    public string Name { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public override string ToString()
    {
        return string.Format("The person with name {0} has password {1} and email {2}",
                             this.Name, this.Password, this.Email);
    }
}

}

However, it is much better to let the built-in serializattion classes do the translation to and from XML for you. The code below needs an explicit reference to the System.Runtime.Serialization.dll. The using statement in itself is not enough:

using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Runtime.Serialization;

namespace XmlSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            var person1 = new Person();
            person1.Name = "Joe";
            person1.Password = "Cla$$ified";
            person1.Email = "[email protected]";

            var person2 = new Person();
            person2.Name = "Doe";
            person2.Name = "$ecret";
            person2.Email = "[email protected]";

            var persons = new[] {person1, person2};

            DataContractSerializer serializer=new DataContractSerializer(typeof(Person[]));
            using (var stream = new FileStream("persons.xml", FileMode.Create, FileAccess.Write))
            {
                serializer.WriteObject(stream,persons);
            }

            Person[] restored_persons;
            using (var another_stream=new FileStream("persons.xml",FileMode.Open,FileAccess.Read))
            {
                restored_persons = serializer.ReadObject(another_stream) as Person[];
            }

            foreach (var person in restored_persons)
            {
                Console.WriteLine(person.ToString());
            }
            Console.ReadLine();
        }
    }

    [DataContract]
    public class Person
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Password { get; set; }
        [DataMember]
        public string Email { get; set; }
        public override string ToString()
        {
            return string.Format("The person with name {0} has password {1} and email {2}",
                                 this.Name, this.Password, this.Email);
        }
    }
}
Dabblernl