How to convert string to XML in C#?
To convert a string to XML in C#, we can use anXmlDocument
object which has a built in method called LoadXml()
which takes the XML as string.Remember to include all namespace:
using System.Text;
, using System.Xml;
, using System.Xml.Serialization;
.Example
using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
public class Program
{
public static void Main()
{
XmlDocument xmltest = new XmlDocument();
string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<myDataz xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<field1>123</field1>
<field2>a</field2>
<field3>b</field3>
</myDataz>";
xmltest.LoadXml(xml);
/* Below code is just to print the content of XML */
Console.WriteLine(xmltest.InnerXml);
}
}