Check for "Root Element is missing", when using XDocument.Parse?
I'd like to hear, how you check for "Root element is missing", when using XDocument.Parse(); Currently, I'm using a try-catch, to catch the error, but I'd like to hear, if any of you have a more clever way to do it - per开发者_高级运维sonally, I'd like to avoid errors, instead of caching them.
I should clarify, the string, which I'm parsing, is returned from WebClient.DownloadString(...);, and therefor, I'm NOT creating the XML myself.
Best regards.
try/catch exception handling is perfectly normal and usual programming style in the .NET framework. And XML has strict syntax rules which the XML parser checks when parsing markup so you need to be prepared to handle any parsing error, try/catch is the right tool for that.
You haven't said whether you control the creation of the string argument you pass to XDocument.Parse. If you don't control it then you can't avoid errors. If you control then make sure you don't use string concatenation or StringBuilders to construct strings with XML, instead make sure you use XML APIs like XmlWriter, that way you would get well-formed XML markup or you would get any error when constructing your markup, not when parsing it. But any errors thrown by XmlWriter are also best handled with try/catch.
精彩评论