Mohanapriya R Mohanapriya R
Updated date Jun 23, 2024
In this article, we will learn how to convert XML documents to strings in C#.
  • 2.7k
  • 0
  • 0

How to Convert XML Documents to Strings in C#?

We can use the built-in methods of C# to read XML documents and convert them to strings easily. We will use the XmlDocument class from the System.Xml namespace to load the XML document, and use the OuterXml property to get the XML content as a string.

The below C# program shows how to convert an XML document to a string:

using System;
using System.Xml;

class Program
{
    static void Main(string[] args)
    {
        // Load XML document
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml("<note><to>Priya</to><from>Mohan</from><body>Hello, Priya!</body></note>");

        // Convert XML document to string
        string xmlString = xmlDoc.OuterXml;

        // Output the converted string
        Console.WriteLine("XML Document as String:");
        Console.WriteLine(xmlString);
    }
}

Output:

XML Document as String:
<note><to>Priya</to><from>Mohan</from><body>Hello, Priya!</body></note>

Comments (0)

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