0

I want to modify some xml files from a given location and I have two methods to do so

Method1-->using XDocument to parse and modify the file

Method2-->using Regex to parse and modify the file

But some files that I want to modify are not a valid xml, so how do I efficiently check for each of the files whether they are modifiable using XDocument or not and perform the operations accordingly like

string[] filesindirectory = Directory.GetFiles(location, "*.xml",SearchOption.AllDirectories);
foreach (string file in filesindirectory)
{
    if(//file is readable/modifiable using XDocument)
    {
        //perform Method1
    }
    else
    {
        //perform Method2
    }
}
FaizanHussainRabbani
  • 3,256
  • 3
  • 26
  • 46
Don_B
  • 243
  • 2
  • 15
  • use `XDocument.parse` if it fails with exception that means it is not valid to be parsed via `XDocument` – Ehsan Sajjad Feb 22 '18 at 14:52
  • @EhsanSajjad is there a better way of checking wihout using an exception – Don_B Feb 22 '18 at 14:53
  • I can't think of any way of knowing if it's good without trying it. Kind of like compiling source code. You have to let something read the code to know if it has errors. It can be a light weight linter, intellisense, or a full compile, but if you don't look at the contents, how are you going to know if they're good or not? Same here. You pretty much have to initiate a parse before you know if it's going to work. Parsing is also the method by which we determine the cause of failure of a parse. You gotta parse it. – Wyck Feb 22 '18 at 14:59
  • This was asked before. See here: https://stackoverflow.com/questions/18704586/testing-whether-or-not-something-is-parseable-xml-in-c-sharp – Element Zero Feb 22 '18 at 15:00

0 Answers0