Mohanapriya R Mohanapriya R
Updated date May 20, 2024
In this program, we will learn how to convert strings into XML documents using C#.

Convert Strings to XML Documents in C#

In this program, we will explore converting strings into XML documents in C#. We will also explore the process with an example and output.

First, let's consider a scenario where you have a string containing XML-like data, but it is not structured as a proper XML document. Perhaps it is data retrieved from an external source or user input. We want to convert this string into a valid XML document that we can manipulate and work within our C# application.

using System;
using System.Xml;

class Program
{
    static void Main(string[] args)
    {
        // Sample string containing XML-like data
        string xmlString = "<book><title>C# Programming</title><author>Ram Kumar</author></book>";

        try
        {
            // Creating an XmlDocument object
            XmlDocument xmlDoc = new XmlDocument();

            // Loading XML string into the XmlDocument
            xmlDoc.LoadXml(xmlString);

            // Output the XML document
            Console.WriteLine(xmlDoc.OuterXml);
        }
        catch (XmlException ex)
        {
            Console.WriteLine("Error: Invalid XML string - " + ex.Message);
        }
    }
}

In this program, we start by defining a string xmlString containing our XML-like data. We then create an instance of XmlDocument and load the XML string into it using the LoadXml method. Finally, we output the XML document using OuterXml.

Output

<book><title>C# Programming</title><author>Ram Kumar</author></book>

Comments (0)

There are no comments. Be the first to comment!!!