Pages: 1
Print
Author Topic: Copy contents from one document into an element with JavaScript Macro  (Read 1473 times)
flopes89
Member

Posts: 1



« on: February 06, 2015, 02:33:24 AM »

I 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 "<Resource filename='FileB.xml'></Resource>"

File B contains arbitrary elements, attributes, CDATA, text, etc.

When opening File A, the macro iterates over all "<Resource>" elements and should copy the contents of the referenced files (through the "filename"-Attribute) into the corresponding "<Resource>" 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();

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?
Logged
Pages: 1
Print
Jump to:  

email us