How to convert from XmlTextWriter to String?

In this post, I will share you a straightforward way to convert XmlTextWriter to string in C#. Check out the following code snippet its self-explanatory

public string CreateXML(string strAuth, string strTran, string strDL, string strCode, string strMsgCode, string strMessage)
{
	string xmlString;
	StringWriter sw = new StringWriter();
	XmlTextWriter writer = new XmlTextWriter(sw);
	// start writing!
	writer.WriteStartDocument();
	writer.WriteStartElement("Result");
	writer.WriteElementString("Authentication", strAuth);
	writer.WriteElementString("Transaction", strTran);
	writer.WriteElementString("DL", strDL);
	writer.WriteElementString("Code", strCode);
	writer.WriteElementString("MsgCode", strMsgCode);
	writer.WriteElementString("Msg", strMessage);
	writer.WriteEndElement();
	//Write XML, and then flush the writer...

	writer.Flush();
	//Return text from string writer...

	xmlString = sw.ToString();
	//close the Objects
	writer.Close();
	sw.Close();
	return xmlString;



}
Reactions

Post a Comment

3 Comments

  1. Nice, thank you!

    ReplyDelete
  2. I thought I would leave the VB.net version for any who are interested...

    Dim xmlstr As String = ""
    Dim sw As New StringWriter()
    Dim writer As New XmlTextWriter(sw)
    writer.WriteStartDocument()
    writer.WriteStartElement("bla")
    writer.WriteElementString("bla1", "bla1value")
    writer.WriteEndElement()
    writer.WriteEndDocument()

    writer.Flush()
    xmlstr = sw.ToString
    writer.Close()

    ReplyDelete

Please do not post any spam link in the comment box😊

Emoji
(y)
:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:P
:o
:>)
(o)
:p
(p)
:-s
(m)
8-)
:-t
:-b
b-(
:-#
=p~
x-)
(k)

Close Menu