Converting String to XmlDocument in C#
To convert a string into an XmlDocument object in C#, we can follow these simple steps:
- Create an instance of XmlDocument: First, we create a new instance of the XmlDocument class.
- Load XML string: We use the
LoadXml()
method of the XmlDocument class to load the XML string into the XmlDocument object. - Access XML content: Once the XML string is loaded, we can access and manipulate the XML content using various properties and methods provided by the XmlDocument class.
C# program:
using System;
using System.Xml;
class Program
{
static void Main(string[] args)
{
// XML string
string xmlString = "<book><title>Principles of Information Systems</title><author>George Reynolds</author></book>";
// Create XmlDocument instance
XmlDocument xmlDoc = new XmlDocument();
// Load XML string
xmlDoc.LoadXml(xmlString);
// Access XML content
XmlNodeList titleNodes = xmlDoc.GetElementsByTagName("title");
foreach (XmlNode titleNode in titleNodes)
{
Console.WriteLine("Title: " + titleNode.InnerText);
}
}
}
In the above program, we have a simple XML string representing a book. We create an XmlDocument instance, load the XML string, and then access the <title>
element using the GetElementsByTagName()
method.
Output:
Title: Principles of Information Systems
Comments (0)