Currently, I have the following c# code to extract a value out of text. If its XML, I want the value within it - otherwise, if its not XML, it can just return the text itself.
String data = "..."
try
{
return XElement.Parse(data).Value;
}
catch (System.Xml.XmlException)
{
return data;
}
I know exceptions are expensive in C#, so I was wondering if there was a better way to determine if the text I'm dealing with is xml or not?
I thought of regex testing, but I dont' see that as a cheaper alternative. Note, I'm asking for a less expensive method of doing this.
As noted by @JustEngland in the comment exceptions are not that expensive, a debugger intercepting them them might take time but in normally they are well performing and good practice. See How expensive are exceptions in C#?.
A better way would be to roll your own TryParse style function:
The DebuggerNonUserCode attribute makes the debugger skip the caught exception to streamline your debugging experience.
Used like this:
I'd have preferred to create an extension method for the TryParse, but you can't create a static one called on a type rather than an instance.
The code given below will match all the following xml formats:
And here's the code:
Calling code:
If you want to know if it's valid, why not use the built-in .NetFX object rather than write one from scratch?
Hope this helps,
Bill
You could do a preliminary check for a < since all XML has to start with one and the bulk of all non-XML will not start with one.
(Free-hand written.)
I originally had the use of a regex but Trim()[0] is identical to what that regex would do.
The way you suggest will be expensive if you will use it in a loop where most of the xml s are not valied, In case of valied xml your code will work like there are not exception handling... so if in most of cases your xml is valied or you doesn't use it in loop, your code will work fine
I find that a perfectly acceptable way of handling your situation (it's probably the way I'd handle it as well). I couldn't find any sort of "XElement.TryParse(string)" in MSDN, so the way you have it would work just fine.