Mohanapriya R Mohanapriya R
Updated date May 20, 2024
In this program, we will explore converting strings to XML in C#. Learn the basics of XML and follow a step-by-step program using the XDocument class.

How to Convert Strings to XML in C#?

In this program, we will see how to convert a string to XML using the XDocument class from the System.Xml.Linq namespace:

using System;
using System.Xml.Linq;

class StringToXmlConverter
    static void Main()
        // Input string representing XML data
        string inputString = "<root><person><name>Raj Kumar</name><age>30</age></person></root>";

            // Parse the string to XML
            XDocument xmlDocument = XDocument.Parse(inputString);

            // Display the XML structure
            Console.WriteLine("Converted XML:");
        catch (Exception ex)
            Console.WriteLine($"Error: {ex.Message}");

This program starts with a sample XML string, represented by inputString. The XDocument.Parse method is then used to convert the string into an XML document. Any parsing errors are caught and displayed to ensure robust error handling.


Converted XML:
    <name>Raj Kumar</name>

Comments (0)

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