Skip to content

Xml Document Creation

Siddhartha Sarkar

Siddhartha Sarkar

Asked May 21, 2009, 9:49 PM EDT2 answers
Share
LinkedInX

Hi All,

I have a situation in which I need to write the XML Declaration of an XmlDocument (that I am creating) from a hard coded text.
How to acieve this? I have tried with the inner text property of XmlDeclaration node etc. but it is throwing errors. Please guide.
I am using C#, however if you can show me the VB way I can very well appreciate that.
Thanks for reading my problem.

Regards,
Sid

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Niradhip Chakraborty
    0
    C#
    using System;
    using System.Xml;
    
    namespace PavelTsekov
    {
     class MainClass
     {
      XmlDocument xmldoc;
      XmlNode xmlnode;
      XmlElement xmlelem;
      XmlElement xmlelem2;
      XmlText xmltext;
      static void Main(string[] args)
      {
       MainClass app=new MainClass();
      }
      public MainClass() //constructor
      {
       xmldoc=new XmlDocument();
       //let's add the XML declaration section
       xmlnode=xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"","");
       xmldoc.AppendChild(xmlnode);
       //let's add the root element
       xmlelem=xmldoc.CreateElement("","ROOT","");
       xmltext=xmldoc.CreateTextNode("This is the text of the root element");
       xmlelem.AppendChild(xmltext);
       xmldoc.AppendChild(xmlelem);
       //let's add another element (child of the root)
       xmlelem2=xmldoc.CreateElement("","SampleElement","");
       xmltext=xmldoc.CreateTextNode("The text of the sample element");
       xmlelem2.AppendChild(xmltext);
       xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);
       //let's try to save the XML document in a file: C:\pavel.xml
       try
       {
        xmldoc.Save("c:\pavel.xml"); //I've chosen the c:\ for the resulting file pavel.xml
       }
       catch (Exception e)
       {
        Console.WriteLine(e.Message);
       }
       Console.ReadLine();
      }
     }
    }
    0
  • Siddhartha Sarkar
    0

    Hi,

     Thanks a lot for your reply. However this was not what I wanted. I wanted, the declaration to be a text that my client provides. not this one: "<?xml version="1.0"?>".

    I have made a work around by appending the declaration as a string before the inner xml of the doc and then reloading the xml in the document.

    Thanks again and I am a fan of James Hetfield too.

    Regards,

    Siddhartha

    0