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
Console.WriteLine(xmlString);
}
static string ConvertXmlNodeToString(XmlNode node)
{
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
node.WriteTo(xmlTextWriter);
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.
Output:
<root><child>Hello, Techiehook!</child></root>
Comments (0)