1

So I'm getting data from a 3rd party in the form of an XML String.

I want to then do the following

messageString = Encoding.ASCII.GetString(messageBeingSent);
messageString = messageString.Trim();

XDocument xmlDoc = XDocument.Parse(messageString);

However, it errors out and gives me the exception hexadecimal value 0x00 is an invalid character. Line 1, Position x where X is the last character in the string.

This appears to me that a null terminator is being sent along with the string and then the XDocument flips out because of the null terminator.

What's the solution to this?

ist_lion
  • 3,149
  • 9
  • 43
  • 73
  • You should consider figuring out what is actully sent and handling it appropriately. I.e. it could be C-style (null terminated) utf-8 string that you try to handle as ASCII string with length... – Alexei Levenkov Dec 02 '11 at 17:00

2 Answers2

2

null character is not valid in XML.

You can pass characters you want to trim:

 messageString.Trim(' ', '\0', ....);
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Aliostad
  • 80,612
  • 21
  • 160
  • 208
-1

I'd have to say it appears the solution is simply

messageString = messageString.replace("0x00", "");

or if you're sure it's nulls:

string s = myEncoding.GetString(bytes.TakeWhile(b => !b.Equals(0)).ToArray());
Dracorat
  • 1,184
  • 7
  • 12
  • 0x00 signifies a null terminator and actually isn't seen in the string. You could in theory copy and paste that text out of the Text Visualizer into notepad, save it as XML and it would be valid. – ist_lion Dec 02 '11 at 16:26
  • 1
    If you're confident it's not actually in the text and it's a superfluous null on the result set, you can use "\0" in the replace, or copy the string to a byte array and copy the bytes back to a string but skip bytes with a value of 0. (Though replacing for "\0" does much the same thing) – Dracorat Dec 02 '11 at 16:29
  • Adding an additional piece of code for this case to the answer. – Dracorat Dec 02 '11 at 16:31