Groups | Blog | Home
all groups > dotnet xml > september 2004 >

dotnet xml : XmlTextWriter without a file



Magnus
9/24/2004 10:49:47 AM
can anyone help me on how to create and manipulate a xmttextwriter without
having to craete a physical file.

I have an application that should return data in xml. But I do not want to
create a file and then delete it.

/Magnus

Martin Honnen
9/24/2004 1:52:25 PM


[quoted text, click to view]

Where does the application need to return the data to? If it needs to
return the data to a stream or network connection you can open an
XmlTextWriter on a stream.
You can also open an XmlTextWriter on a MemoryStream and create the XML
in memory.
Or you can ceate an XmlTextWriter on a StringWriter and simply read out
the string at the end as in the following example:

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("gods");
xmlWriter.WriteElementString("god", "Kibo");
xmlWriter.WriteEndDocument();
xmlWriter.Close();
Console.WriteLine(stringWriter.ToString());

which writes

<?xml version="1.0" encoding="utf-16"?><gods><god>Kibo</god></gods>

to the console.

--

Martin Honnen
Magnus
9/24/2004 2:38:56 PM
Hi. Thanks.

That was what I wanted.

One other thing: How can I change the encoding to UTF-8 or ISO-8859-1
on StringWriter the encoding property is readonly, and on XmlTextWriter I
can not set the encoding type.

Do I have to so a search and replace?

/Magnus

[quoted text, click to view]

Martin Honnen
9/24/2004 3:14:30 PM


[quoted text, click to view]

A string in .NET/C# is always UTF-16 encoded as far as I know so it
doesn't make sense to enforce another encoding if you are dealing with
strings.
If you don't want an XML declaration in that string then you can avoid
calling WriteStartDocument e.g. simply write elements as needed:

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.WriteStartElement("gods");
xmlWriter.WriteElementString("god", "Kibo");
xmlWriter.WriteEndElement();
xmlWriter.Close();
Console.WriteLine(stringWriter.ToString());

--

Martin Honnen
AddThis Social Bookmark Button