Converting Strings to XML Nodes:
C# provides the System.Xml
namespace, which contains classes and methods for working with XML data. One of the key classes is XmlDocument
, which represents an XML document and provides methods for loading, creating, and manipulating XML data.
To convert a string into XML nodes, we can use the XmlDocument
class along with the LoadXml()
method. This method loads the XML data from the specified string and creates an XML document object.
using System;
using System.Xml;
class Program
{
static void Main(string[] args)
{
string xmlString = "<book><title>C# Programming</title><author>Sumit Kumar</author></book>";
// Create an XML document
XmlDocument xmlDoc = new XmlDocument();
try
{
// Load XML from string
xmlDoc.LoadXml(xmlString);
// Display XML nodes
XmlNodeList nodeList = xmlDoc.DocumentElement.ChildNodes;
foreach (XmlNode node in nodeList)
{
Console.WriteLine(node.Name + ": " + node.InnerText);
}
}
catch (XmlException ex)
{
Console.WriteLine("Invalid XML string: " + ex.Message);
}
}
}
In the above program, we first define an XML string representing a book with title and author information. We then create an XmlDocument
object and load the XML data from the string using the LoadXml()
method. Then, we iterate through the child nodes of the root element (<book>
) and display their names and inner text.
Output:
title: C# Programming
author: Sumit Kumar
Comments (0)