Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear all content in XmlTextWriter and StringWriter

I want to clear all of content in XmlTextWriter and StringWriter. Flush() didn't work out.

XmlDocument doc = new XmlDocument(); StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(sw);

xw.WriteStartElement("AddPhoneQual"); xw.WriteElementString("Type", "B"); xw.WriteElementString("PhoneNumber", bookingDetails.PassengerList[0].PhoneNumber); xw.WriteEndElement(); // End AddPhoneQual

doc.LoadXml(sw.ToString());

Now, i need to clear all of content and start to write in clear xw.

xw.Flush(); sw.Flush();

They didn't work.

like image 414
sdeligoz Avatar asked Oct 11 '12 12:10

sdeligoz


People also ask

How to clear StringWriter in c#?

Remove(0, sb. Length); // your StringWriter is now empty! This worked for me (in the same situation as you -- using an XmlTextWriter that dumps to the StringWriter ).

How do you clear a StringWriter in Java?

The flush() method of StringWriter Class in Java is used to flush the writer. By flushing the writer, it means to clear the writer of any element that may be or maybe not inside the writer. It neither accepts any parameter nor returns any value. Parameters: This method does not accepts any parameter.


1 Answers

You'd think there would be an intuitive way to do this, but....

A solution I found suggests the following:

// make a StringWriter, and fill it with junk
StringWriter sw = new StringWriter();
sw.Write("Don't want to see this");

// and HERE IS THE MAGIC
StringBuilder sb = sw.GetStringBuilder();
sb.Remove(0, sb.Length);

// your StringWriter is now empty!

This worked for me (in the same situation as you -- using an XmlTextWriter that dumps to the StringWriter).

Perhaps somebody has an intuitive answer for why nothing like this is built-in.

like image 157
Michael Paulukonis Avatar answered Oct 02 '22 20:10

Michael Paulukonis