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>";
try
{
// Parse the string to XML
XDocument xmlDocument = XDocument.Parse(inputString);
// Display the XML structure
Console.WriteLine("Converted XML:");
Console.WriteLine(xmlDocument.ToString());
}
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.
Output:
Converted XML:
<root>
<person>
<name>Raj Kumar</name>
<age>30</age>
</person>
</root>


Comments (0)