How to check if a string is an XML before calling LoadXML(str)?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

hi there, in VB LoadXML(str) returns true or false so that you can do
different coding when the str is XML or not, but in C# LoadXML doesn't have
return but only throw exception if str is not XML document. How would I do if
I want to do my own code if str is not an XML? thanks!
 
cloudx said:
hi there, in VB LoadXML(str) returns true or false so that you can do
different coding when the str is XML or not, but in C# LoadXML doesn't have
return but only throw exception if str is not XML document. How would I do if
I want to do my own code if str is not an XML? thanks!

Anything wrong with catching the exception? It seems the simplest way
to me.
 
If you start to parse the whole infoset to see if it is all valid xml, then
you may as well LoadXML as that what it does anyway. If you want a quick
check/guess, test to see if first char of string is "<". If not, you know
it is not xml. You don't know it is valid xml either, but the load will
tell you that. You may want to Trim() the string first just to remove any
leading or trailing spaces and test for Empty first, then for leading "<"
char.
 
I am new to C# so I might be asking some silly questions. The issue is that
if the str is not XML then I would like to do something else instead of being
kicked out by exception. Thanks!
 
Catching an Exception is not necessarily being "kicked out." While it's not
the most efficient way to handle an error, it certainly wouldn't be that
drastic. For example:

try
{
LoadXML(str);
... // do something with the XML
}
catch (XmlFormatException e)
{
// it wasn't XML if we get here, so do the other thing
}
finally
{
CloseXML();
}

/m
 
Back
Top