Click here to Skip to main content
Click here to Skip to main content

Tagged as

Easy to Use XML-Writer Class C#

, 26 Nov 2013 GPL3
Rate this:
Please Sign up or sign in to vote.
This is an easy to use class that will help you in creating and reading XMLfiles.

Introduction

By using my XamLister class, you will be able to easily create and read custom XmlFiles, no matter how big they are.

Background

I've been programming in C# since August 2013 and found myself writing the same methods (XmlWrite() and XmlLoad()) again and again.

One day, I learned how to create my own classes and decided to write a few classes that will lighten my workload.

Using the Code

My class consists of only two methods, Write() and Read().

The Write() method needs two lists, two strings, and an XmlWriterSettings object to work properly.

Write(List of Nodes, List of Content (same Order!), Destination Path as string, 
Start Element as String, XmlWriterSettings xms)

It is important that both Lists are in the same order, like this:

Nodelist: (Name (0), Surname(1), Address(3))  Contentlist: (Mark (0), Saltberg(1), San Diego(3)) 

The first Item in the Nodelist will be allocated to the first Item in the Contentlist, etc.

The return value will be a Tuple containing a:

  • Boolean (true, if the writing process was successful and false if it was not)
  • string ("Success" if everything went fine, but containing the Exception if not)

If you do not know how to work with a Tuple, take this as an example:

For example, our Xamlister object is called xlist.

First, you'll need to define an empty variable:

var emptyvar 

Now you can put the return values of xlist.Write() into this variable.

var emptyvar = xlist.Write()

and you can read out both items in emptyvar like this:

bool result = emptyvar.Item1;
string Resultstring = emptyvar.Item2;

The second method is the Read(string Source) method.

This one is very easy, you call it with the Source-XML file you want to read the elements from, the return value is also a Tuple, but this one contains a boolean (true for success and false for failure) and a List of Strings, these are the Element contents of the XML file.

The first element in the list is Startelement, an EndElement is not included.

Reading the values out of this Tuple is as easy as in the first method:

bool result = emptyvar.Item1;
List<string> ResultList = emptyvar.Item2;

 public Tuple<bool, string> Write(List<string> Nodelist, 
 List<string> Contentlist, string Dest, string Startelement, 
 XmlWriterSettings xms)
        {
            try
            {
                if (Contentlist.Count != Nodelist.Count)
                {
                    return Tuple.Create<bool, string>
                    (false, "Your Nodelist does not match the Contentlist!");
                }
                XmlWriter wr = XmlWriter.Create(Dest, xms);
               

                int x = Nodelist.Count;
                int i = 0;

                wr.WriteStartElement(Startelement);
                while (i <= x-1)
                {
                    wr.WriteElementString(Nodelist.ElementAt(i), Contentlist.ElementAt(i));
                    i++;
                }
                wr.WriteEndElement();
                wr.Close();
               
                return Tuple.Create<bool, string>(true, "Success");
            }
            catch (Exception ex)
            {
                return Tuple.Create<bool, string>(false, ex.ToString());
               
            }
        }
 public Tuple<bool, List<string>> Read(string Source)
    {

        List<string> Contentlist = null;
        bool Success = false;
        try
        {


            XmlReader re = XmlReader.Create(Source);
            if (re.Read() == true)
            {
                re.ReadStartElement();
            }
            while (re.Read())
            {
                try
                {
                    Contentlist.Add(re.ReadContentAsString());
                }
                catch (Exception ext) //################# Could not find 
                			// a way for better error handling
                {
                    try
                    {
                        Contentlist.Add(re.ReadElementContentAsString());
                    }
                    catch (Exception ext2)
                    {
                        Contentlist.Add(re.ReadString());
                    }
                }
            }
            re.Close();
            Success = true;


            return Tuple.Create(Success, Contentlist);
        }
        catch (Exception ex)
        {
            Success = false;
            Contentlist.Add(ex.ToString());
          
            return Tuple.Create(Success, Contentlist);
        }
    }
       public Tuple<bool, string> Write(List<string> 
Nodelist, List<string> Contentlist, string Dest, string Startelement)
        {
            try
            {
                if (Contentlist.Count != Nodelist.Count)
                {
                    return Tuple.Create<bool, string>
                    (false, "Your Nodelist does not match the Contentlist!");
                }
                XmlWriterSettings xms = new XmlWriterSettings();
                xms.Indent = true;
                xms.NewLineOnAttributes = true;

                XmlWriter wr = XmlWriter.Create(Dest, xms);


                int x = Nodelist.Count;
                int i = 0;

                wr.WriteStartElement(Startelement);
                while (i <= x - 1)
                {
                    wr.WriteElementString(Nodelist.ElementAt(i), Contentlist.ElementAt(i));
                    i++;
                }
                wr.WriteEndElement();
                wr.Close();

                return Tuple.Create<bool, string>(true, "Success");
            }
            catch (Exception ex)
            {
                return Tuple.Create<bool, string>(false, ex.ToString());

            }
        } 
} 

Points of Interest

This class is compatible with nearly every XML file, but it's important that you know the order of the elements you are writing the content to or reading from.

History

  • V 0.1 - 26.11.2013
  • V 0.2 - 29.11.2013

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

Feverbird
Student Student
Germany Germany
No Biography provided

Comments and Discussions

 
AnswerProblems with the architecture PinprofessionalFeverbird28-Nov-13 5:35 
General[My vote of 2] Some issues with the architecture PinmemberJohn Brett26-Nov-13 22:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.141022.2 | Last Updated 26 Nov 2013
Article Copyright 2013 by Feverbird
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid