Monday, May 16, 2011

Write XML Document Programmatically Using C#

In this article simply I will try to explain, how to write an XML document using c#. Extensible Markup Language(XML) was designed to transport and store data, with focus on what data is[1].  I think sometimes programmer needs to write XML document from other source of data. In my article I try to do that as a simple manner.



Case Study: For a test case, suppose I have some data (may be it store in a database or somewhere else) and i write an XML document with these data. For my case my data store in a ListArray.

The following steps are followed:
Step1: I have two List one store question and another store answer of the question.

List<string> questionList = new List<string>(){"Who is the writer of Gitanjolee?"};
List<String> answerList = new List<string>(){"Kaji Najrul Islam","Rabindronath Tagure","Jasim Uddin","Saratchondro"};

Now i write the XML file with these List. the structure of the file will be
<?xml version="1.0"?>
<XMLWrite>
    <Questions>
        <Question>
            <Text><![CDATA[Who is the writer of Gitanjolee?]]></Text>
        </Question>
        <Answers>
            <Answer>
                <Text><![CDATA[Kaji Najrul Islam]]></Text>
            </Answer>
            <Answer>
                <Text><![CDATA[Rabindronath Tagure]]></Text>
            </Answer>
            <Answer>
                <Text><![CDATA[Jasim Uddin]]></Text>
            </Answer>
            <Answer>
                <Text><![CDATA[Saratchondro]]></Text>
            </Answer>
        </Answers>
    </Questions>
</XMLWrite>

Step2: Write the following method to write the XML document.

       private void WriteXMLFile()
        {
            //file name to store XML data
            string fileName = "QuestionTestXML__" + DateTime.Now.ToString("yyyyMMddhhmmss");
                     
            XmlDocument doc = new XmlDocument();

            // XML declaration
            XmlNode declaration = doc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
            doc.AppendChild(declaration);

            // Root element: XMLWrite
            XmlElement root = doc.CreateElement("XMLWrite");
            doc.AppendChild(root);

            // Sub-element: Questions
            XmlElement Questions = doc.CreateElement("Questions");

            //Sub-element of Questions: Question
            foreach (var item in LstQuestion)
            {
                XmlElement Question = doc.CreateElement("Question");
              
                //Sub-element of Question:Text
                XmlElement Text = doc.CreateElement("Text");
                XmlNode cTextdata = doc.CreateCDataSection(item);
                Text.AppendChild(cTextdata);
                Question.AppendChild(Text);
                              
                //Sub-element of Question:Answers
                XmlElement Answers = doc.CreateElement("Answers");
                //Sub-element of Answers:Answer
                foreach (var answer in LstAnswer)
                {
                    XmlElement AnswerForQuestion = doc.CreateElement("Answer");
                  
                    //Sub-element of Answer:Text
                    XmlElement AnswerText = doc.CreateElement("Text");
                    XmlNode cAnswerTextdata = doc.CreateCDataSection(answer);
                    AnswerText.AppendChild(cAnswerTextdata);
                    AnswerForQuestion.AppendChild(AnswerText);

                    Answers.AppendChild(AnswerForQuestion);

                }
                Question.AppendChild(Answers);
                Questions.AppendChild(Question);

            }

            root.AppendChild(Questions);

            doc.Save(Server.MapPath(@"~/App_Data/" + fileName));

        }

The explanation of the method is as follows:
  1. First I create a unique file name in which I want to save my document.
  2. Create the XmlDocument object doc. For use XmlDocument object add the System.Xml namespace.
  3. Create the XML declaration using XmlDocument's  CreateNode method and add the declaration in the doc.
  4. Create the root element with the name XMLWrite and add it to the doc.
  5. Create the sub element Questions.
  6. Create the sub element of Questions with the name Question
  7. //Sub-element of Question:Text
                    XmlElement Text = doc.CreateElement("Text");               
          XmlNode cTextdata = doc.CreateCDataSection(item);
                    Text.AppendChild(cTextdata);
                    Question.AppendChild(Text);
    using this code segment i create a xml element Text, create CDATA for the Text element and add the Text element to the Question node.

  8.                //Sub-element of Question:Answers                XmlElement Answers = doc.CreateElement("Answers");
                    //Sub-element of Answers:Answer
                    foreach (var answer in LstAnswer)
                    {
                        XmlElement AnswerForQuestion = doc.CreateElement("Answer");
                      
                        //Sub-element of Answer:Text
                        XmlElement AnswerText = doc.CreateElement("Text");
                        XmlNode cAnswerTextdata = doc.CreateCDataSection(answer);
                        AnswerText.AppendChild(cAnswerTextdata);
                        AnswerForQuestion.AppendChild(AnswerText);

                        Answers.AppendChild(AnswerForQuestion);

                    }
    Using this code segment i create an Answers element. Now pick one answer from the answer list append it in the Answer element of Answers node.
Finally I use root.AppendChild(Questions); to append the question node to the root node.

Now i save my document in App_Data folder with my desired file name using the following line
doc.Save(Server.MapPath(@"~/App_Data/" + fileName));. You may use your desired location. That's all.

Any suggestion, advice or query please write me in a mail.



Shimul Mahmud
azkhairuzzaman@gmail.com



1 comment:

  1. i want to create xml file programmaticaly in c using c functions only....i don't want to use .net etc. can you help me?

    ReplyDelete