Mohanapriya R Mohanapriya R
Updated date Jun 13, 2024
In this article, we will learn how to convert XML nodes to strings in C#.

 Convert XML Nodes to Strings in C#

When working with XML data in C#, it's common to need to convert XML nodes to strings for various purposes such as logging, serialization, or data manipulation. In the below program, we will explore how to achieve this conversion easily.

using System;
using System.IO;
using System.Xml;

class Program
    static void Main(string[] args)
        // Create an XML document
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<root><child>Hello, TechieHook!</child></root>");

        // Get the root node
        XmlNode root = doc.DocumentElement;

        // Convert the root node to a string
        string xmlString = ConvertXmlNodeToString(root);

        // Output the string

    static string ConvertXmlNodeToString(XmlNode node)
        StringWriter stringWriter = new StringWriter();
        XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
        return stringWriter.ToString();

In this program, we have created an XmlDocument and loading it with a simple XML string. Then, we retrieved the root node of the XML document. The ConvertXmlNodeToString method took an XmlNode as input and returned its string representation.


<root><child>Hello, Techiehook!</child></root>

Comments (0)

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