Mohanapriya R Mohanapriya R
Updated date May 18, 2024
In this article, we will learn how to easily parse XML data in C# by converting strings into XML elements.
  • 2.6k
  • 0
  • 0

Convert Strings to XML Elements in C#

The below C# program shows how to convert strings to XML elements in C#,

using System;
using System.Xml.Linq;

class Program
{
    static void Main(string[] args)
    {
        // XML string to be converted into an XML element
        string xmlString = "<book><title>C# Programming</title><author>Mohan Kumar</author></book>";

        try
        {
            // Convert the XML string into an XML element
            XElement xmlElement = XElement.Parse(xmlString);

            // Output the converted XML element
            Console.WriteLine("Converted XML Element:");
            Console.WriteLine(xmlElement);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error occurred: " + ex.Message);
        }
    }
}

We have a simple XML string representing a book with a title and an author. We use the XElement.Parse method to convert this string into an XML element. If the conversion is successful, we will print the output XML element to the console.

Output

Converted XML Element:
<book><title>C# Programming</title><author>Mohan Kumar</author></book>

Comments (0)

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