Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Easy to Use XML-Writer Class C#

0.00/5 (No votes)
26 Nov 2013 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here