I have a byte array in a C# program.
I want to determine as quickly as possible if the content is Xml. If it's the case, I also want to return the Xml itself.
By now I have this method :
protected bool TryGetXElement(byte[] body, out XElement el)
{
el = null;
// if there is no data, this is not xml :)
if (body == null || body.Length == 0)
{
return false;
}
try
{
// Load the data into a memory stream
using (var ms = new MemoryStream(body))
{
using (var sr = new StreamReader(ms))
{
// if the first character is not <, this can't be xml
var firstChar = (char)sr.Peek();
if (firstChar != '<')
{
return false;
}
else
{
// ultimately, we try to parse the XML
el = XElement.Load(sr);
return true;
}
}
}
}
catch
{
// if it failed, we suppose this is not XML
return false;
}
}
Is there potential improvement?
<
. Moreover, as it's computer XML, i'm confident it wiki never starts with a sppace – Steve B Sep 12 '12 at 8:56