The goal of this tutorial is to write a macro that removes all namespace prefixes from the active document. To add a macro you have to switch to the XMLSpyFormEditor. Use "Tools | Switch to scripting environment" to show the main window of the form editor. If the scripting environment was not installed before, you have to do it now.
Open the XMLSpyMacros module with a double-click on the tree item in the project window. Use the "Add Function" command either from the "Project" menu, or from the popup menu which appears if you right-click the module in the project bar:
Type in "RemoveNamespaces" for the macro name in the following dialog. XMLSpyFormEditor creates a new macro and adds it to the (XMLSpyMacros) module.
Note that macros don't support parameters or return values. There is therefore no function header. Enter the code below in the macros window:
if(Application.ActiveDocument != null) {
RemoveAllNamespaces(Application.ActiveDocument.RootElement);
Application.ActiveDocument.UpdateViews();
}
We now have to write the RemoveNamespaces function. Place this function into the global declarations module, so that it is accessible from our macros, events and forms.
Activate the (GlobalDeclarations) module and add the RemoveNamespaces() function to any previously defined global variables and functions as follows:
function RemoveAllNamespaces(objXMLData)
{
if(objXMLData == null)
return;
if(objXMLData.HasChildren) {
var objChild;
// spyXMLDataElement := 4
objChild = objXMLData.GetFirstChild(4);
while(objChild) {
RemoveAllNamespaces(objChild);
try {
var nPos,txtName;
txtName = objChild.Name;
if((nPos = txtName.indexOf(":")) >= 0) {
objChild.Name = txtName.substring(nPos+1);
}
objChild = objXMLData.GetNextChild();
}
catch(Err) {
objChild = null;
}
}
}
}
This completes the creation of the new macro. You can run it from the "Show macros..." dialog in the "Tools" menu of XMLSpy.
The sample can be easily extended to perform renaming instead of removing of the namespaces. Design a form (see also "How to create a form") where the user can specify the old and the new namespace names. Then change the try-catch-block of the RemoveAllNamespaces() function to something like this:
try {
var nPos,txtName;
txtName = objChild.Name;
if((nPos = txtName.indexOf(":")) >= 0) {
var txtOld;
txtOld = txtName.substring(0,nPos);
if(txtOld == txtOldNamespace)
objChild.Name = txtNewNamespace + ":" + txtName.substring(nPos+1);
}
objChild = objXMLData.GetNextChild();
}
catch(Err) {
objChild = null;
}
This code assumes that txtOldNamespace and txtNewNamespace are declared as globals and are set with the proper values.
Previous
Top
Next