Main Site Documentation

XMLWriter WriteElementString exception


#1

Hi guys,

any idea why


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

throws a null reference exception ?


#2

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.


#3

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");

	xmlwrite.Flush();
	xmlwrite.Close();

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


#4

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?


#5

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.


#6

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.


#7

I guess this is a bug then.

The overloads do work:


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

//works
WriteElementString(string, string, string);
WriteElementString(string, string, string, string);

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


#8

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.


#9

You can just use this for now:
xmlwrite.WriteStartElement(“test”);
xmlwrite.WriteString(“data”);
xmlwrite.WriteEndElement();

We will report the problem to Microsoft.


#10

Thanks Mike for following up :wink: