AaronReams
asked on
How to write XML data to a string not to a file?
Hi Y'all,
I'm in a bit of a rush here and trying to figure out how to write XML data to a string/buffer rather than a file. This is what I'm been trying. Am I way off?
MemoryStream ms = new MemoryStream();
XmlTextWriter tw = new XmlTextWriter(ms, Encoding.UTF8 );
tw.WriteStartDocument();
tw.WriteStartElement("Clie ntRequest" );
tw.WriteString("Test");
tw.WriteEndElement();
tw.WriteEndDocument();
byte[] buf = new byte[ms.Length];
ms.Seek(0,SeekOrigin.Begin );
ms.Read(buf,0,(int)ms.Leng th);
string request = System.Text.Encoding.UTF8. GetString( buf,0,buf. Length);
Many thanks!
Aaron
I'm in a bit of a rush here and trying to figure out how to write XML data to a string/buffer rather than a file. This is what I'm been trying. Am I way off?
MemoryStream ms = new MemoryStream();
XmlTextWriter tw = new XmlTextWriter(ms, Encoding.UTF8 );
tw.WriteStartDocument();
tw.WriteStartElement("Clie
tw.WriteString("Test");
tw.WriteEndElement();
tw.WriteEndDocument();
byte[] buf = new byte[ms.Length];
ms.Seek(0,SeekOrigin.Begin
ms.Read(buf,0,(int)ms.Leng
string request = System.Text.Encoding.UTF8.
Many thanks!
Aaron
That looks good, just don't forget to call ms.Close() after you get the string to free up the resources.
ASKER
it might look good but unfortunately it doesn't work... any thoughts?
ASKER
btw, ms.Length = 0 at the byte buffer allocation line. do i need to do something different to initialize my XmlTextWriter?
ASKER
Uh, I figured this out on my own courtesy of the following link...
http://www.artisticode.com/Articles/45.aspx
MemoryStream ms = new MemoryStream();
XmlTextWriter tw = new XmlTextWriter(ms, Encoding.UTF8 );
tw.Formatting = Formatting.Indented;
tw.Indentation = 4;
tw.WriteStartDocument();
tw.WriteStartElement("Clie ntRequest" );
tw.WriteString("Test");
tw.WriteEndElement();
tw.WriteEndDocument();
tw.Flush();
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string request = sr.ReadToEnd();
http://www.artisticode.com/Articles/45.aspx
MemoryStream ms = new MemoryStream();
XmlTextWriter tw = new XmlTextWriter(ms, Encoding.UTF8 );
tw.Formatting = Formatting.Indented;
tw.Indentation = 4;
tw.WriteStartDocument();
tw.WriteStartElement("Clie
tw.WriteString("Test");
tw.WriteEndElement();
tw.WriteEndDocument();
tw.Flush();
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string request = sr.ReadToEnd();
ASKER
and thanks to all that looked at this question. also thanks to thedude112286 for your suggestion. peace.
I think I used a StringBuilder and a StringWriter - but then you get a unicode string which is UTF16.
ASKER
Uh, I was able to figure this out on my own and I posted the solution above.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.