General XMetaL Discussion
XMetaL Community Forum › General XMetaL Discussion › Copy contents from one document into an element with JavaScript Macro
-
flopes89 February 6, 2015 at 8:33 am
Copy contents from one document into an element with JavaScript Macro
February 6, 2015 at 8:33 amParticipants 1Replies 0Last Activity 7 years, 12 months agoI have the task of copying the contents of a document into an element of the current document.
The basic setup is:
File A contains element “
“ File B contains arbitrary elements, attributes, CDATA, text, etc.
When opening File A, the macro iterates over all “
” elements and should copy the contents of the referenced files (through the “filename”-Attribute) into the corresponding “ ” element. What I came up with so far:
On_Document_Open_Complete
[code]function main() {var initialDocument = ActiveDocument;
// Current path to resolve relative external filenames
var path = initialDocument.Path;// Find all external resource elements
var nodes = initialDocument.getNodesByXPath(“//ExternalRessource”);// Make sure we have nodes to process
if (nodes == null || nodes.length == 0) {
return;
}var nodeCount = nodes.length;
for (var currentIndex = 0; currentIndex < nodeCount; currentIndex++) {
var node = nodes.item(currentIndex);
Application.SetStatusText(“Processing external element [” + (currentIndex + 1) + ” of ” + nodeCount + “] (” + node.nodeName + “)”);// Get the attribute of the current node to use as filename
var externalName = node.getAttribute(“filename”);if (externalName == null || externalName == “”) {
continue;
}if (!Application.ReadableFileExists(externalName)) {
Application.Alert(“No readable file [” + externalName + “] exists!”);
return;
}// Load the referenced file
var externalString = Application.FileToString(externalName);if (externalString == “”) {
Application.Alert(“Could not open external file [” + externalName + “]”);
return;
}// Now, we select all contents of the file and copy it
var externalDocument = Documents.OpenString(externalString);
var externalRange = externalDocument.Range;
externalRange.SelectAll();
externalRange.Copy();// … and paste it into the current node
var range = initialDocument.Range;
range.SelectNodeContents(node);
range.Paste();externalDocument.Close(sqDoNotSaveChanges);
}
}main();
[/code]But, I get an “Node cannot be selected” error, which I don't understand. Why can the node not be selected? What am I doing wrong?
-
AuthorPosts
- You must be logged in to reply to this topic.