Creating a xml file by using xmldocument object in c#.net

Creating a xml file by using xmldocument object in c#.net

        We will use XmlDocument class to create xml file on the fly. We will first make the xml document in memory with XmlDocument object. Then we will use it’s save method which will save the content as a XML file at the file location provided. Lets start

Here we want to get an XML file with content as below

<ROOT>
  <InstallationId>00000000-0000-0000-0000-000000000000</InstallationId>
  <Environment>Dev</Environment>
  <InstallationPath>D:\Users\App.exe</InstallationPath>
</ROOT>

Creating a xml file by using xmldocument object in c#.net

C# code to make an XML file with above content is

      string ConfigFilePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + “\\app.config”;
      if (!File.Exists(ConfigFilePath))
      {
        // Create <Root> Node
        XmlDocument docConfig = new XmlDocument();
        XmlNode xmlNode = docConfig.CreateNode(XmlNodeType.XmlDeclaration, “”, “”);
        XmlElement rootElement = docConfig.CreateElement(“ROOT”);
        docConfig.AppendChild(rootElement);

        // Create <InstallationId> Node
        XmlElement installationElement = docConfig.CreateElement(“InstallationId”);
        XmlText installationIdText = docConfig.CreateTextNode(Guid.Empty.ToString());
        installationElement.AppendChild(installationIdText);
        docConfig.ChildNodes.Item(0).AppendChild(installationElement);

        // Create <Environment> Node
        XmlElement environmentElement = docConfig.CreateElement(“Environment”);
        XmlText environText = docConfig.CreateTextNode(“Dev”);
        environmentElement.AppendChild(environText);
        docConfig.ChildNodes.Item(0).AppendChild(environmentElement);

         // Create <InstallationPath> Node
        XmlElement environmentPathElement = docConfig.CreateElement(“InstallationPath”);
        XmlText environPathText = docConfig.CreateTextNode(Assembly.GetExecutingAssembly().Location);
        environmentPathElement.AppendChild(environPathText);
        docConfig.ChildNodes.Item(0).AppendChild(environmentPathElement);

        // Save xml document to the specified folder path.
        docConfig.Save(ConfigFilePath);
      }

Leave a Comment