Clear all content in XmlTextWriter and StringWriter
Asked Answered
I

1

12

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.

Inaccuracy answered 11/10, 2012 at 12:51 Comment(0)
D
17

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.

Devastate answered 4/12, 2012 at 15:47 Comment(3)
It's been pointed out (thanks, @PeteB) that you can initialize StringBuiler with a length, allowing us to simplify by replacing the two StringBuilder lines with: sw.GetStringBuilder().Length = 0;Devastate
Or you could just do sw.GetStringBuilder().Clear();Extrados
I don't like it, but it works. Thanks!Backbencher

© 2022 - 2024 — McMap. All rights reserved.