XMLWriter WriteElementString exception

Hi guys,

any idea why

xmlwriter.WriteElementString("ID", "23");

throws a null reference exception ?

Check to make sure your xmlwriter object is not null. The only other exception I’ve seen with this method is an invalid operation if your xml is not well formed.

the exception i get is:

using this code:

public static void Main()
	MemoryStream ms = new MemoryStream();
	XmlWriter xmlwrite = XmlWriter.Create(ms);
	xmlwrite.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
	xmlwrite.WriteElementString("test", "data");


	//////// display the XML data ///////////
	byte[] byteArray = ms.ToArray();
	char[] cc = System.Text.UTF8Encoding.UTF8.GetChars(byteArray);
	string str = new string(cc);

What line throws the exception? My guess would be this one:

char[] cc = System.Text.UTF8Encoding.UTF8.GetChars(byteArray);

You need to reset the stream pointer to zero before getting the byte array. I’m a little confused as to why you would write the xml to a stream to just display it as a string again. Is the last chunk of code just to prove the writer is behaving?

The line that throws the exception:

xmlwrite.WriteElementString("test", "data");

and yes, it is just to look at the produced xml doc.
Later on this will be send over a tcp socket.

Hmm… I debugged through this and am stumped. I replaced the problem line with this

xmlwrite.WriteString ("<test>data</test>");

and it does not write that to the stream and does not throw an exception! I ended up with an empty xml doc:

<?xml version="1.0" encoding="utf-8"?>

There isn’t anything obviously wrong with your code. You can get the netmf source and debug through that to see what is throwing the exception. There is definately something fishy going on in MFDpwsExtensions.

I guess this is a bug then.

The overloads do work:

//throws null reference exception
WriteElementString(string, string);

WriteElementString(string, string, string);
WriteElementString(string, string, string, string);

Maybe Gus and/or team can sched some light here.

I use these libraries quite a bit, so if nobody else speaks up here, I’ll debug through the source and report it to MS, if necessary.

You can just use this for now:

We will report the problem to Microsoft.

Thanks Mike for following up :wink: