public void MigrateIfRequired(XDocument document, string xmlFile) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var root = document.Root; if (document.Root == null) { throw new XmlSchemaValidationException("The XML file is invalid."); } var version = int.Parse(document.Root.GetAttribute("version", "0")); if (version == 0) { // Verison 0 is the XML before it was verisoned from 1.0b. // Add the version and namespace declaration so it will match verison 1. document.Root.Add(new XAttribute("version", 1)); foreach (var element in document.Descendants()) { element.Name = element.Name.LocalName.GetElementName(); } version = 1; document.Save(xmlFile); } // Check that the XML is up to date. if (version < XmlVersion) { // Ensure that the file is valid for it's version xmlValidator.ValidateXml(version, xmlFile); var migrations = storageMigrations.Where(x => x.MigratesToVersion > version) .OrderBy(x => x.MigratesToVersion); foreach (var migration in migrations) { migration.Migrate(root); } var versionAttribute = root.Attribute("version"); if (versionAttribute != null) { versionAttribute.Value = XmlVersion.ToString(CultureInfo.InvariantCulture); } SanitizeXml(document.Root); document.Save(xmlFile); } xmlValidator.ValidateXml(XmlVersion, xmlFile); }
public IConversionResult ConvertFile(string path) { XDocument documentToConvert; try { documentToConvert = _reader.ReadDataFromFile(path); } catch (Exception exception) { return(HandleExceptionFromReadingFile(exception, path)); } var validationResult = _validator.ValidateXml(documentToConvert); return(validationResult.Item1 ? PerfromConversionForDataDocument(documentToConvert, path) : ReportValidationFailure(validationResult)); }