Create Xml string using Memorystream in C#

Madhu.B.Rokkam
Posted by Madhu.B.Rokkam under C# category on | Points: 40 | Views : 100941
public static void Main()
{
string resultString = GetInputXml();
Console.WriteLine(resultString);
Console.Read();
}

private static string CreateXml()
{
MemoryStream memoryStream = null;
XmlTextWriter xmlTextWriter = null;
StreamReader streamReader = null;
string xmlOutput = string.Empty;

try
{
memoryStream = new MemoryStream();
xmlTextWriter = new XmlTextWriter(memoryStream, System.Text.Encoding.UTF8);

//xmlTextWriter.WriteStartDocument();
xmlTextWriter.Formatting = Formatting.Indented;

xmlTextWriter.WriteStartElement("Root");

xmlTextWriter.WriteElementString("Id", "1001");
xmlTextWriter.WriteElementString("Status", "Closed");
xmlTextWriter.WriteElementString("SourceID", "S001");
xmlTextWriter.WriteFullEndElement();
xmlTextWriter.Flush();

memoryStream.Position = 0;
streamReader = new StreamReader(memoryStream);
xmlOutput = streamReader.ReadToEnd();

xmlTextWriter.Close();
streamReader.Close();
}
catch (Exception ex)
{
throw new ApplicationException("Error creating input xml in GetInputXml method.");
}
return xmlOutput;
}



Output:

<Root>
<Id>1001</Id>
<Status>Closed</Status>
<SourceID>S001</SourceID>
</Root>

Comments or Responses

Login to post response