Skip to content

Instantly share code, notes, and snippets.

@SKalt
Last active May 14, 2017 19:45
Show Gist options
  • Save SKalt/91b9822573e8ec648ba967ade6649807 to your computer and use it in GitHub Desktop.
Save SKalt/91b9822573e8ec648ba967ade6649807 to your computer and use it in GitHub Desktop.
SchemaLocation replacer
/**
* Correct all schemaLocation paths with new relative or absolute paths to the
* .xsd files.
* @param {String} inputStr a string of an .xsd file to reprocess
* @param {String|Object} dirOrLocations a string directory containing all
* imported/included schemas or an object mapping the current schema filename
* with an optional extension .xsd to a new location
* @returns {String} the xsd file with all schemaLocations replaced with
* corrected relative or absolute paths
* @throws {Error} throws an error if schema location translations are missing
*/
function replaceSchemaLocations(inputStr, dirOrLocations){
let re = /([^="]\/){0,1}(([^"=\/]+)\.xsd)/ig;
var replacer;
if (typeof(dirOrLocations) == 'object'){
let locations = dirOrLocations;
replacer = (match, p1, p2, p3) => {
let result = locations[p2] || locations[p3];
if (!result){
throw new Error('no schema location specified for ' + p2);
}
return result;
};
return inputStr.replace(re, replacer);
} else if (typeof(dirOrLocations) == 'string'){
let dir = dirOrLocations;
replacer = (match, p1, p2, p3) => dir + '/' + p3;
} else {
throw new Error('no schema locations / schema directory supplied');
}
return inputStr.replace(re, replacer);
}

Libxml2 runs libxmljs in javascript and lxml in python. Those tools all provide schema validation methods that are liable to break after .xsd files are moved or directory structure changes. This function allows easy renaming of schemaLocation attributes to repair such .xsd address changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment