XMLImportPreference

Hi,
trying to set XML import preferences on Document or Application but it keeps on giving me error. Syntax is really simple, I used it several times for PDF exporting options and similar but this time doesn't seem to work... any bug?
I'm working with InDesign CS3 (mac) and scripting in javaScript.
Here's the code...
with(app.XMLImportPreference)
ignoreWhitespace = true;
importToSelected = false;
createLinkToXML = true;
repeatTextElements = true;
ignoreUnmatchedIncoming = true;
ignoreWhitespace = true;
removeUnmatchedExisting = true;
Thanks anticipately!
C.

Hi C.,
Use app.xmlImportPreferences, and it should work.
Thanks,
Ole

Similar Messages

  • Open XML and using xslt with JavaScript

    Hello,
    I want the user to be able to choose an XML-file. This XML-file should not be placed in InDesign, there is not even a document needed for my script. All I need is a variable, containing the file. However, the XML-file should be transformed with xslt into another XML-file. How do I do this?
    This is how I open the first XML-file, the one that should be transformed:
       var xmlDoc = File.openDialog ("Choose XML");
       if (xmlDoc == null) {return;}
        xmlDoc.open("r");
        xmlDoc = xmlDoc.read();
        xmlDoc = new XML(xmlDoc);
    I can adress different nodes and use xmlDoc as an XML-file, so that's fine, but how do I transform it?
    I read the Scripting Guide and tried this:
        var myDocument = app.documents.add();
        var myXMLImportPreferences = app.xmlImportPreferences;
        myXMLImportPreferences.transformFilename = "c:\myTransform.xsl";
        var xx = myDocument.importXML(File.openDialog ("XML"));
    However, it's not exactly what I want since I have to create a document and it's not working either, since xx stays undefined.
    Thanks for your help.

    You can't get exactly what you want.
    Your first code example uses the InDesign JavaScript interpreter's XML support, called E4X. It has absolutely nothing to do with the InDesign document object model or InDesign's internal support for XML. It exists only within the JavaScript interpreter. It does not support XSLT transformations.
    Your second example leverages InDesign's built-in XSLT support (I'm not too sure how this works...); but that is only useful when importing XML into
    InDesign, which, as you have learned, requires a document.
    In the first example, you could call out to an external invokation of xsltproc and read in the input. How to do that differs for Windows and Mac.
    In the second example, you could export the XML from your Document back out to an XML file and read it back in with E4X.
    None of this is very appealing. What do you really need to do?

  • InDesign server crashes every time when calling deleteEmptyPages in script

    We are evaluting InDesign Server CS6 on a Windows server environment. We have an idml file, sample xml file that is tagged to specific frames inside the idml file and a script file for execution on the server. This script opens the idml file using the app.open api, imports the xml file and export the ID file to a PDF. Because we have table content with variable row count, we are using the smart text reflow functionality. Setting the text preferences with smart text reflow appears to be working but we also want to delete the empty second page when the content is less than a page. So, we also tried using the deleteEmptyPages property document's textPreferences. When this is set to true and the script is executed on the ID server using the sampleclient, the server crashes with the following message. When I do the same thing in the InDesign UI using the preferences options, it works as expected.
    The script looks like below - is this the right way to do it?
    var myInddFile = app.scriptArgs.get("idfile"); //"X:/IDFiles/AutoFlow.indd";
    var myXmlFile = app.scriptArgs.get("xmlfile"); //"X:/IDFiles/deleteme.xml";
    var myOutputOptions = "[Smallest File Size]";
    var myPDFPreset = app.pdfExportPresets.itemByName(myOutputOptions);
    var myDoc = app.open (File(myInddFile), OpenOptions.OPEN_COPY);
    myDoc.xmlImportPreferences.ignoreWhitespace = true;
    myDoc.textPreferences.smartTextReflow = true;
    //myDoc.textPreferences.addPages = AddPageOptions.END_OF_STORY;
    //myDoc.textPreferences.limitToMasterTextFrames = true;
    myDoc.importXML (File(myXmlFile));
    //uncommenting this line causes the ID server to crash
    //myDoc.textPreferences.deleteEmptyPages = true;
    var myOutputFile = app.scriptArgs.get("outputfile");//File("X:/IDFiles/sampleX.pdf")
    myDoc.exportFile (ExportFormat.PDF_TYPE,myOutputFile, myPDFPreset)

    Thanks Harbs. We are looking at full automation and so removing the pages manually is not an option. But I did find a script at InTools http://in-tools.com/article/scripts-blog/script-of-the-day-jan-24-2010/ that helps with automating the removal of empty pages. This script appears to be a nice workaround for server side usage. I used it on my document with multiple column text frames and it is removing the empty page as expected. If there is a better way to do this, let me know. Thanks.

  • XML Won't Transform in Batch [JS, CS3]

    When I use import xml manually into indesign, it works - but when I import it using the script below, it does not apply the transformation.
    Any ideas?
    with(app.activeDocument.xmlImportPreferences) {
            allowTransform = true;
            transformFilename = XMLTransformFile.STYLESHEET_IN_XML;
            createLinkToXML = false;
            ignoreWhitespace =true;
            ignoreUnmatchedIncoming = false;
            importCALSTables = true;
            importToSelected = false;
            allowTransform = false;
           importTextIntoTables = true;   
           repeatTextElements = false;
           removeUnmatchedExisting = false;
           importStyle = XMLImportStyles.MERGE_IMPORT;

    arrgh, this was not was i wanted to test: it works with cs3 if you omit the with {} statement.
    if you set the xmlImportPreferences direct it does work here.
    app.activeDocument.xmlImportPreferences.allowTransform = true;
    app.activeDocument.xmlImportPreferences.transformFilename = XMLTransformFile.STYLESHEET_IN_XML;
    so this is not working:
    var _file = File.openDialog ("Choose XML File");
    with(app.activeDocument.xmlImportPreferences) {
            allowTransform = true;
            transformFilename = XMLTransformFile.STYLESHEET_IN_XML;
            //transformFilename = File.openDialog ("Choose XSL File");
    app.activeDocument.importXML(_file);
    but this works fine:
    var _file = File.openDialog ("Choose XML File");
    app.activeDocument.xmlImportPreferences.allowTransform = true;
    app.activeDocument.xmlImportPreferences.transformFilename = XMLTransformFile.STYLESHEET_IN_XML;
    //transformFilename = File.openDialog ("Choose XSL File");   
    app.activeDocument.importXML(_file);

  • [CS5 Win] Switching to InDesign is slow in CS5 for certain documents. XML links?

    Hi,
    I put this question in the scripting part, since you might be the ones to notice such things as this, and it might relate to importing XML by scripting. Also I got no positive response in one of the other forums, "complaining" about the sluggish performance redrawing the interface when setting focus to InDesign CS5. But now I can more clearly see that it is not slow for all documents.
    Having certain documents open in InDesign CS5 makes it very slow to switch to. The CPU peaks at 80-100% and it takes about a second or two until InDesign responds.
    The documents do not necessarily need to be large in size, but it appears that it mostly occurrs on documents that I've imported data to (or that our customers have), using our own code, which takes care of an XML file and portions it out into templates.
    One strange thing I just noticed was that selecting "relink all" by alt-clicking the relink button in the Links palette, makes InDesign look for (presumalbly) previously imported XML files. How can that be?
    I never store any links to the imported XML - as far as I know. Where should I look for that kind of links?
    How and why would previously imported XML file paths be stored? I just import the XML into the structure, "deal with it", and deletes the node that it was imported to. (The data is left in a structure that I build up myself.)
    Does anyone know if there is a change related to any of the facts stated above, in InDesign CS5?
    I'll attach a screen shot of the links dialogue (above), when it "looks for" an XML file. Could this kind of "missing file" cause the abovementioned "slowness" every time switching to InDesign from another application?
    (InDesign documents that don't relate to XML doesn't make switching to InDesign slow - but it gets slow when such a document is loaded, even under a tab that is not in focus.)
    Best regards,
    Andreas

    I've uploaded a video to demonstrate that InDesign sometimes can keep references to links:
    http://www.youtube.com/watch?v=OoQOSIlfYl4
    It's obvious that there are thousands of "orphans" in the documents. All XML files ever imported are kept in some way... The links (or the names of them) are obviously not removed from the document when deleting the Element in the XML Structure. Since the communication of the code with a database is built around XML import, the number of imported files is very large.
    Can these orphaned link references somehow be removed? When manually checking for missing files, InDesign loops though all of the XML files as seen in the YouTube video above, but ends up saying that there are no missing files. The next time I do the same check, all links are looped through again.
    Perhaps we should "link to file", using .xmlImportPreferences.createLinkToXML = true
    This propery has not been explicitly set, and therfore = false. But is there any way to get rid of all the old link names that's inside the document somehow?
    CS4 does the same thing, but there is "no 2 second lag time" switching from another application to InDesign CS4 with this kind of document open.

  • InDesign CS2 - don't want to ignore Whitespace elements

    Hi,
    I am working of InDesign CS2 on XP-SP2, while doing manual XML import i can successfully uncheck "Do not import contents of whitespace-only elements" but i can't do the same using script....
    I am using following chunk of script in CS2 which doesn't work with ESTK2.
    mydoc.xmlImportPreferences.ignoreWhitespace = false;
    I noticed this works well with CS3 plugins in CS2. I need to resolve this with CS2 only. Let me know if you have any clue.
    Thanks.

    Under Document Offset, specify the number of lines that are to be ignored at the beginning of the document.
    This enables you to skip comment lines or column names during processing. If you do not make an entry, the default value is zero lines.
    http://help.sap.com/saphelp_nw04/helpdata/en/2c/181077dd7d6b4ea6a8029b20bf7e55/frameset.htm
    But in Receiver File adapter
    NameA.addHeaderLine=0
    is used to have no Header line in the target structure
    http://help.sap.com/saphelp_nw04/helpdata/en/2c/181077dd7d6b4ea6a8029b20bf7e55/frameset.htm

  • [JS][CS3] Trying to use XSL to transform a XML document

    I´m trying to do a script to format my XML in a particular way. The XSL document is ok because I´ve used this document to format an XML document in Indesign CS3 and works fine.However, when I´m trying to use this document in my scripting method I can´t obtain my XML formatted. I´ve tried it many times but I really don´t know where is the problem.
    I´ve changed the XMLExportPreferences (allowTransform,TransformFileName)in my scripting method before exporting my XML in order to obtain a formatted XML.
    Anyone have any idea? What are the steps to make this work?
    Thank u,
    Peter

    I'm having a similar problem but with importing XML. When I run this script I get a dialogue saying that "Stylesheet 'Macintosh HD:Users:myFolder:transform.xsl, specified in the XSLT processing instruction can not be found." But this is the location of the stylesheet??
    Here's the entire script (a combination of Adobe samples):
    main();
    function main(){
    mySetup();
    mySnippet();
    function mySetup(){
    var myDocument = app.documents.add();
    var myRootXMLElement = myDocument.xmlElements.item(0);
    var myXMLTag = myDocument.xmlTags.add("body");
    var myXMLElement = myDocument.xmlElements.item(0).xmlElements.add(myXMLTag);
    myDocument.select(myXMLElement);
    //Sets XML import options.
    var myXMLImportPreferences = myDocument.xmlImportPreferences;
    myXMLImportPreferences.createLinkToXML = false;
    myXMLImportPreferences.ignoreUnmatchedIncoming = false;
    myXMLImportPreferences.ignoreWhitespace = true;
    myXMLImportPreferences.importCALSTables = true;
    myXMLImportPreferences.importStyle = XMLImportStyles.mergeImport;
    myXMLImportPreferences.importTextIntoTables = false;
    myXMLImportPreferences.importToSelected = true;
    myXMLImportPreferences.removeUnmatchedExisting = false;
    myXMLImportPreferences.repeatTextElements = true;
    myXMLImportPreferences.allowTransform = true;
    myXMLImportPreferences.transformFilename = File("/Users/myFolder/transform.xsl");
    myDocument.importXML(File("/Users/myFolder/document.xml"))
    function mySnippet(){
    var myDocument = app.documents.item(0);
    myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;
    myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
    myDocument.viewPreferences.rulerOrigin = RulerOrigin.pageOrigin;
    myDocument.xmlElements.item(0).xmlElements.item(0).placeIntoFrame(myDocumen pages.item(0), [35, 35, 758, 576]);

  • [JS - CS3 - Mac OS] XML import preferences: xslt file issue...

    Hi,
    I know there's a bug on Mac about this, does anybody knows if is there another way to do it?
    I'm importing an XML file and I need to transform it with an XSLT stylesheet.
    Here's the code:
    var xmlFile = new File("/User/Desktop/product.xml");
    var xsltFile = new File("/User/Desktop/stylesheet.xsl");
    with(app.activeDocument.xmlImportPreferences){
         transformFilename = xsltFile;
    myNode.importXML(xmlFile);
    Pretty simple but ID is missing my xsl file...
    I'm really bored about this, hope there's an alternative solution...
    Thanks anticipately.

    Hi Thomas
    I've learnt a lot since my last posting, so thanks for putting me on the right track then.
    I have actually tried what you suggested. I had the same problem with the XML file path when it was hard coded. The object being that I just wanted to replace a static xml doc.
    Where I've got      set xmlpath to choose file with prompt "Select the XML"
    i also had             set xsltpath to choose file with prompt "Select the XSLT"
                               log xsltpath --(this throws the value of xsltpath in to the results pane of AS)
    It still didn't work. It showed the correct path to the file but still failed when run through the script. Bizzare!
    The only other thing that I could try is to just define xsltpath as "CWtoINDDElements.xsl", due to the fact that I've told InDesign that I'm getting the XML from the same folder in the 'choose' function.
    I'm not connecting to my work VPN at 11.50pm, so I'll try again in the morning.
    Thanks Thomas. It's great to bounce ideas around.
    Best, Andrew

  • Importing xml is not working

    Hello i am trying to import an xml file into a document but its not allowing the import.
    Let me clarify a bit, i have allready imported the same xml in about 50-60 different documents without any problems, but now i have a document that does not allow me to import the xml.
    After looking a bit deeper i found the following:
    You can see that the parameter "Only import elements that match existing structure" is checked. When i uncheck this param, the xml is imported correctly.
    Now i tried to simulate is via scripting but with no success.
    Here's what i tried:
    InDesign.app.xmlImportPreferences.importToSelected = true;
    InDesign.app.xmlImportPreferences.importStyle = XMLImportStyles.MERGE_IMPORT;
    InDesign.app.xmlImportPreferences.ignoreUnmatchedIncoming = false;

    And the document import xml settings are the same as in the screenshot? Also, you are using extendscript, my example is actionscript and i've noticed quite some differneces between the 2 in the past (although they use the same API).
    Edit: There is also the fact that i didnt test your code ( ignorent as i am) and didnt see that your example actually DOES work. Thank you very much for your help,
    On a sidenote: can you explain me why it works if you call:
    InDesign.app.activeDocument.xmlImportPreferences
    but not when you call:
    InDesign.app.xmlImportPreferences
    My thought was that when you call it on the document, then it's only for the current document, but when you call it on the application, then it is for all documents that get processed by that application.
    Is this wrong? Or is it the way it is meant to be?

  • Import XML... vs .importXML [JS CS4]

    I'm looking to programmatically import an XML file, but the results are not what I expected.
    For example, take this file, sample.xml
    <persons>
       <person pid="0">
         <name>John Q. Public</name>
         <age>54</age>
         <date string="birthday">
           <day>14</day>
           <month>May</month>
           <year>1956</year>
         </date>
       </person>
       <person pid="1">
         <name>Sally Smith</name>
    If I run this code, importSample.jsx
    // a new document was already programmatically created
    var myDocument = app.documents.item(0);
    myDocument.xmlElements[0].importXML(File(Folder.desktop + "/sample.xml"));
    I get this:
    But if I use File > Import XML... I get this, which is what I want:
    The examples I'm finding for scripting XML import are all the same – most results for scripting turn up Adobe's own PDF guides. The XML rules examples in the InDesign CS4 Scripting Guide PDF (Javascript) uses similar XML in its example, but requires it to be imported already. What am I missing here?

    First off, thanks for the reply!
    Perhaps a few basic checks are in order:
    * is your sample.xml saved as plain text? (I suppose it is, because ID itself can read it. Check anyway, will you?)
    As sample.xml or sample.txt, as UTF-8 with or without the BOM – no go.
    * are you sure the file opened in your script is the one you intended? I put the XML file in the Scripts folder, and used this for path:
    myDocument.xmlElements[0].importXML(File(app.activeScript.path + "/sample.xml"));
    If I remove the one I think I'm using on the Desktop it gives me a modal window saying the file can't be found. I tried the above path with a copy of the XML in the same folder as the script with the same results.
    * ... can't think of anything else ...
    (Ed.) My version is not showing any XML contents, but that's because it's a preference which accidentally was "off" on my system. It's still the same.
    Running the script doesn't "open" the XML tree in the Structures panel. If you open the Root item, it shows "persons" but not its contained items. However, since I saw the little triangle on the left, I knew there was more to it and opened that too. Perhaps ... your InDesign forgot to draw that "there-is-more" triangle!
    Did you know clicking the Open triangle with the Alt button down (on a Mac) also opens all elements within? I just found that accidentally ... (Plenty surprises left, I guess.)
    I clicked, option-clicked, command-clicked, command-option clicked... where the disclosure triangle next to "persons" should be, and no results. Clicking the same way on "Root" only discloses "persons". (That's a cool trick for showing all items though.)
    If I select "persons" and choose "New Element..." from the Structure Panel menu I get a choice of:
    person
    persons
    Root
    I can't add more to the newly created "person" in the same (or any) way. Options at higher levels remain the same.
    Is one of these wrong?
    function setXMLPrefs(){
       var myDocument = app.documents.item(0);
       // XML View Preferences
       var myXMLViewPreferences = myDocument.xmlViewPreferences;
       myXMLViewPreferences.showAttributes = true;
       myXMLViewPreferences.showStructure = true;
       myXMLViewPreferences.showTaggedFrames = true;
       myXMLViewPreferences.showTagMarkers = true;
       myXMLViewPreferences.showTextSnippets = true;
       // XML Import Prefs
       var myXMLImportPreferences = myDocument.xmlImportPreferences;
       myXMLImportPreferences.allowTransform = false;
       myXMLImportPreferences.createLinkToXML = false;
       myXMLImportPreferences.ignoreUnmatchedIncoming = true;
       myXMLImportPreferences.ignoreWhitespace = true;
       myXMLImportPreferences.importCALSTables = true;
       myXMLImportPreferences.importStyle = XMLImportStyles.mergeImport;
       myXMLImportPreferences.importTextIntoTables = false;
       myXMLImportPreferences.importToSelected = false;
       myXMLImportPreferences.removeUnmatchedExisting = false;
       myXMLImportPreferences.repeatTextElements = true;

  • How to shift content with in cell in xml rules table

    Hi all scripters,
    I've created a table using xml rules with 3 nos of cells where first cell contain some data and so on but in next row first cell may of may not contain any data so in that row second cell data shifted to first cell and thired row data shifted to second cell which is very anxious for me since second cell data in each row should be in second cell only.
    For Instance-: Required output
    Title
    PageNo
    Subject
    Title
    46
    The Subject
    50
    Another Subject
    54
    Subject
    Title
    60
    Another Subject
    64
    The subject
    The out put I am getting by script-:
    Title
    PageNo
    Subject
    Title
    46
    The Subject
    50
    Another Subject
    54
    Subject
    Title
    60
    Another Subject
    64
    The subject
    myRuleSet = new Array ( new ProcessSec,
               new ProcessPara,
               new ProcessSecHead,
               new ProcessArt,
               new ProcessPG,
    with(myDocument){
        var elements = xmlElements;
         __processRuleSet(elements.item(0), myRuleSet);
    function ProcessSecHead(myXPath){
        this.name = "ProcessSecHead";
        this.xpath = myXPath;
        this.apply = function(myElement, myRuleProcessor){
       with(myElement){
                __skipChildren(myRuleProcessor);
                  var myNewElement = myContainerElement.xmlElements.item(-1).xmlElements.add(app.documents.item(0).xmlTags.item("Cell"));
         myElement.move(LocationOptions.atBeginning, myContainerElement.xmlElements.item(-1).xmlElements.item(-1));
        return true;
    function ProcessPara(){
        this.name = "ProcessPara";
        this.xpath = "//para";
        this.apply = function(myElement, myRuleProcessor){
                var myNewElement = myContainerElement.xmlElements.add(app.documents.item(0).xmlTags.item("Row"));
            return true;
    function ProcessArt(){
        this.name = "ProcessArt";
        this.xpath = "//para/aug";
        this.apply = function(myElement, myRuleProcessor){
            with(myElement){
                __processChildren(myRuleProcessor);
                var myNewElement = myContainerElement.xmlElements.item(-1).xmlElements.add(app.documents.item(0).xmlTags.item("Cell"));
                myElement.move(LocationOptions.atBeginning, myNewElement);  
            return true;
    function ProcessPG(myXPath){
        this.name = "ProcessPG";
        this.xpath = myXPath;
        this.apply = function(myElement, myRuleProcessor){
            with(myElement){
                __skipChildren(myRuleProcessor);
                var myNewElement = myContainerElement.xmlElements.item(-1).xmlElements.add(app.documents.item(0).xmlTags.item("Cell"));
                myElement.move(LocationOptions.atBeginning, myNewElement);
            return true;
    Any would be greatly appreciated
    Mac

    Wow, sorry for the delay.
    This paradigm is difficult enough to deal with, but Adobe's example code really does not encourage you to handle this reasonably at all.
    I've basically rewritten the entire process, and I've introduced a new paradigm for creating rules that I think is a lot more readable and flexible and allows for parametrization. Anyhow, here you go. Any questions?
    /*jslint undef: true, newcap: true, nomen: false, regexp: true,
            bitwise: true, onevar: true, indent: 4, white: false */
    /*global File, LocationOptions, PageSideOptions,
      UserInteractionLevels,
      __processChildren, __processRuleSet, alert, app */
    #include "glue code.jsx";
    // handy debugging function; e.g.: $.writeln(dumplist(x.xmlElements));
    function dumplist(l) {
        var i, rv = [];
        rv.push("has "+l.length+" elements:");
        for (i=0; i<l.length; i++) {
            rv.push("  "+i+"\t"+l[i].toSpecifier()+
                        "\t"+l[i].markupTag.name);
        return rv.join("\n");
    // Initialize a tags object to map strings to tags.
    function initTags(doc, tagnames) {
        var i, t, tags = {};
        for (i=0; i<tagnames.length; i++) {
            try {
                t = doc.xmlTags.add(tagnames[i]);
            } catch (e0) {}
            tags[tagnames[i]] = doc.xmlTags.itemByName(tagnames[i]);
         return tags;
    // Handy subtree functions
    function firstChildTag(node, tag) {
        var i, e = node.xmlElements;
        for (i=0; i<e.length; i++) {
            if (e[i].markupTag === tag) {
                return e[i];
        return node;
    function lastChildTag(node, tag) {
        var i, e = node.xmlElements;
        for (i=e.length-1; i>=0; i--) {
            if (e[i].markupTag === tag) {
                return e[i];
        return node;
    //// XML rule functions
    // Adobe's sample for how to define these is HORRIBLE.
    // Let's fix several of these problems.
    // First, a handy object to make clearer the return values
    // of XML rules:
    var XMLmm = { stopProcessing: true, continueProcessing: false};
    // Adobe suggest defining rules constructors like this:
    //   function RuleName() {
    //       this.name = "RuleNameAsString";
    //       this.xpath = "ValidXPathSpecifier";
    //       this.apply = function (element, ruleSet, ruleProcessor){
    //       //Do something here.
    //       //Return true to stop further processing of the XML element
    //       return true;
    //       }; // end of Apply function
    // And then creating a ruleset like this:
    //   var myRuleSet = new Array (new RuleName, new anotherRuleName);
    // That syntax is ugly and, and is especially bad if
    // you need to parametrize the rule parameters, which is the only
    // reasonable approach to writing reasonable rules. Such as:
    //   function addNode(xpath, parent, tag) {
    //       this.name = "addNode";
    //       this.xpath = xpath;
    //       this.apply = function (element, ruleProcessor) {
    //           parent.xmlElements.add(tag);
    //           return XMLmm.stopProcessing;
    // and then creating a ruleset like:
    //   rule = new Array (new addNode("//p", someTag));
    // So instead we introduce a makeRule function, that
    // allows us to leave behind all the crud. So then we can write:
    // addNode = makeRule("addNode",
    // function(element, ruleProcessor, parent, tag) {
    //     parent.xmlElements.add(tag);
    //     return XMLmm.stopProcessing;
    // and use:
    // rule = [ addNode("//p", someTag ];
    function makeRule(name, f) {
        return function(xpath) {
            var
                //xpath=arguments[0],
                   // "arguments" isn't a real array, but we can use
                   // Array.prototype.slice on it instead...
                   args=Array.prototype.slice.apply(arguments, [1]);
            return {
                name: name,
                xpath: xpath,
                apply: function(element, ruleProcessor) {
                        // Slice is necessary to make a copy so we don't
                        // affect future calls.
                    var moreargs = args.slice(0);
                    moreargs.splice(0, 0, element, ruleProcessor);
                    return f.apply(f,moreargs);
    // Create a new node at parent. Doesn't do
    // anything with the XPath context node.
    var addNode = makeRule("addNode",
    function(element, ruleProcessor, parent, tag) {
        parent.xmlElements.add(tag);
        return XMLmm.stopProcessing;
    // Create a cell for a table, adding a node to
    // the last node of the last node of the
    // table. Duplicate the context
    // node as a child of that cell.
    var makeCell = makeRule("makeCell",
    function(element, rp, table, outertag, innertag) {
        var
            cell = table.xmlElements[-1].xmlElements.add(outertag),
            copy = element.duplicate();          
        copy.markupTag = innertag;
        copy.move(LocationOptions.AT_BEGINNING, cell);
        return XMLmm.stopProcessing;
    // Apply from() to the context node to get
    // a source node. Copy that source node
    // to be the first child of the context node.
    var copyFromToChild = makeRule("copyFromToChild",
    function(element, ruleProcessor, from) {
        var copy = from(element).duplicate();       
        copy.move(LocationOptions.BEFORE,
          element.xmlElements[0]);   
        // __skipChildren(ruleProcessor);
        return XMLmm.continueProcessing;
    // We don't actually use this, but it was useful
    // in debugging. Essentially "rename" a node.
    // Set the tag of the context node to the
    // specified tag.
    var setTag = makeRule("setTag",
    function(element, ruleProcessor, newtag) {
        element.markupTag = newtag;
        return XMLmm.stopProcessing;
    // Apply from() to the context node to get
    // a source node. Apply to() to the
    // context node to get a destination node.
    // Move the source node in the specified
    // location (how) to the destination node.
    var moveFromTo = makeRule("moveFromTo",
    function (element, ruleProcessor, from, how, to) {
        __processChildren(ruleProcessor);
        var src = from(element);
        src.move(how, to(element));
        return XMLmm.continueProcessing;
    // end rule functions
    // It's just not worth rewriting some of Adobe's ugly functions...
    // but at least fix it up so it JSLints.
    function myGetBounds(myDocument, myPage){
        var
            myPageWidth = myDocument.documentPreferences.pageWidth,
            myPageHeight = myDocument.documentPreferences.pageHeight,
            myX1, myX2, myY1, myY2;
        if(myPage.side === PageSideOptions.leftHand){
            myX2 = myPage.marginPreferences.left;
            myX1 = myPage.marginPreferences.right;
        else{
            myX1 = myPage.marginPreferences.left;
            myX2 = myPage.marginPreferences.right;
        myY1 = myPage.marginPreferences.top;
        myX2 = myPageWidth - myX2;
        myY2 = myPageHeight - myPage.marginPreferences.bottom;
        return [myY1, myX1, myY2, myX2];
    function myGetScriptPath() {
        try {
            return app.activeScript;
        catch(myError){
            return new File(myError.fileName);
    // OK, the actual program.
    function main() {
        var
            doc = app.activeDocument,
            page = doc.pages[0],
            root = doc.xmlElements[0],
            //inputFile = new File(myGetScriptPath().path+ "/mac.xml"),
            inputFile = File.openDialog(),
            tags = {},
            p, table;
        if (app.documents.length<1) {
           alert ("Open a document and run the Script");
           return false;
         // Let's not use a seperate variable for each tag. Instead,
         // we'll keep an Object that maps strings to tags.
        tags = initTags(doc,
                             ["table", "para", "article",
                              "section", "section-head", "tr", "td", "p"]);
        doc.xmlImportPreferences.allowTransform = false;
        doc.xmlImportPreferences.ignoreWhitespace = true;
        app.scriptPreferences.userInteractionLevel =
              UserInteractionLevels.NEVER_INTERACT;
        doc.importXML(inputFile);
        app.scriptPreferences.userInteractionLevel =
              UserInteractionLevels.INTERACT_WITH_ALL;
        // For each <para>, copy the parent's <section-head> inside.
        // Next, move each <article> node to the end of the <para>,
        // placing it after the <page> node.
        __processRuleSet(root, [
            copyFromToChild(
                "//para",
                function(n) {
                        return firstChildTag(n.parent,tags["section-head"]);
            moveFromTo(
                "//para",
                function(n) { return firstChildTag(n, tags.article); },
                LocationOptions.AT_END,
                // This is more general than we need to be; we're moving
                // to "the end", but the end of WHAT? It need not be the
                // <para>, it could be some other node.
                function(n) { return n; })
        // Add a <p> node to hold the table we're about to create.  It's
         // not super-clear from the documentation, but
         // convertElementToTable creates a text node of the table in the
         // XLM structure. In order to then place that into a frame, there
         // has to be an enclosing XML node to do so. We choose <p> for
         // lack of a better tag.
        p = root.xmlElements.add(tags.p);
        table = p.xmlElements.add(tags.table);
        // For each para node, add a <tr> to the table.  For each
        // <section-head>, <page>, or <article>, add a <td> to the last
        // <tr> of the table
        __processRuleSet(root, [
            addNode("//para", table, tags.tr),
            makeCell("//para/section-head", table, tags.td, tags.p),
            makeCell("//para/page", table, tags.td, tags.p),
            makeCell("//para/article", table, tags.td, tags.p)
         // Make it a table and GO!
        table.convertElementToTable(tags.tr, tags.td);
        p.placeIntoFrame(page, myGetBounds(doc, page));
    main();
    I also tried to format this to 72 columns so that it doesn't scroll on the forums. Let's see if that works...Nope, not quite. Oh well. Close enough.

  • XML Importscript to InDesign?

    Hello Forum,
    I'm just searching for a solution to import a few XML-files into InDesign.
    Each XML-file is about one theme.
    So it is much work to import each xml-file one by one into InDesign (up to 300 files).
    Do you know a possibility to import the whole XML-files by a java-script?
    I only found export-scripting, but no import.
    I'll be very, very glad, if you can help me!!
    Greetings,

    The big consideration in importing XML is setting the XML preferences correctly. For an append import you can modify the following function which requires a reference to the active document as its only parameter:
    function xmlAppendPrefs (docRef){
    var xmlPrefs = docRef.xmlImportPreferences;
    xmlPrefs.createLinkToXML = false;
    xmlPrefs.allowTransform = false;
    xmlPrefs.ImportStyle = XMLImportStyles.APPEND_IMPORT;
    xmlPrefs.repeatTextElements = false;
    xmlPrefs.importToSelected = false;
    xmlPrefs.ignoreWhitespace = true;
    xmlPrefs.ignoreUnmatchedIncoming = false;
    xmlPrefs.importCALSTablbes = false;
    xmlPrefs.importTextIntoTables = false;
    Assuming you have an array of XML file references, you then iterate through the array to import the files. The next function makes sure that the fileRef reference passed is a file but does not check to make sure the file exists. The function expects a reference to the active document and the file reference (fileRef) as its parameters.
    function importXMLFile (docRef, fileRef) {
    try {
    if (fileRef instanceof File) {
    docRef.importXML(fileRef);
    } else {
    docRef.importXML(File(fileRef));
    } catch (e) {
    throw (e);
    You will want to make sure that your XML files do not repeat the Root tag. If they all share the same similar structure, you should have no problem.
    For instance, if the file structures all begin with <story>, your structure will end up with <Root><story>story contents here</story><story>another story contents here</story></Root>.
    Hope this helps,
    Shirley Hopkins                           

  • Data Truncate document.importXML()

    Hello,
    after opening an InDesign Template, and importing  XML, the new content has less data than the original one.
    The content that is truncated is a texFrame with 2 columns.
    The original template has some tags to match the xml :
    dates and airports. If the dates are too long, the match still works, but then some data is truncate, and there is no overflow red signal.
    var advertDoc;
    var location = "path to template";
    var xmlLocation = "path to xml file";
    try {
        var templateFile = File(location);
        var xmlTemplate =  File(xmlLocation);
         if(templateFile.exists && xmlTemplate.exists) {
            advertDoc = app.open(templateFile);
           // here I can see all the data 
            //set import xml options
            var xmlImportPreferences = advertDoc.xmlImportPreferences;
            xmlImportPreferences.importStyle = XMLImportStyles.mergeImport;
            xmlImportPreferences.createLinkToXML = false;
            xmlImportPreferences.allowTransform = false;
            xmlImportPreferences.repeatTextElements = false;
            xmlImportPreferences.ignoreUnmatchedIncoming = true;
            xmlImportPreferences.ignoreWhitespace = true;
            xmlImportPreferences.importCALSTables = true;
            xmlImportPreferences.importTextIntoTables = false;
            xmlImportPreferences.importToSelected = false;
            xmlImportPreferences.removeUnmatchedExisting = true;
            xmlImportPreferences.repeatTextElements = true;
            advertDoc.importXML(xmlTemplate);
            // some data missing
    } catch (err) {
    Also when I use the duplicate function for a Group some data get lost
    var module = moduleDoc.layers.itemByName("Modules").groups[0];
    var duplicatedModule = module.duplicate(templateDoc.layers.itemByName("Modules")); 
    moduleDoc and templateDoc are well formed, and have all the necessary elements.
    So my question are:
    1) Is there any restriction on importXML and duplicate functions for the amount of data?
    2) Why I can not see any error signal?
    Thanks in advanced.

    How about if you cut the data length to the maximum allowed column length? Let us assume that you have a varchar2 column with 250 width. Then you can insert this value:
    substr(yourData,1,250)Message was edited by:
    Sven W.

  • Iterate through XML tags of file (CS5)

    Hello!
    I'd like to iterate through an XML file, but I am not sure how to do this, since the import is mostly done automatically.
    This is how I load and import the file:
    var f = new File('~/Desktop/test.xml');
    app.activeDocument.importXML(f);  
    But how can I now iterate through its tags using JavaScript?

    Hallo,
    Thank you for the resource!
    However, I was not able to implement any of the example because of an error "__processRuleSet is not a function".
    My code is:
    //Setup.jsx
    mainSetup();
    function mainSetup(){
         var myDocument = app.documents.add();
         myDocument.xmlImportPreferences.allowTransform = false;
         myDocument.xmlImportPreferences.ignoreWhitespace = true;
         var myFilePath = '~/Desktop/test.xml';
         myDocument.importXML(File(myFilePath));
         var myBounds = myGetBounds(myDocument, myDocument.pages.item(0));
         myDocument.xmlElements.item(0).placeIntoFrame(myDocument.pages.item(0), myBounds);
         function myGetBounds(myDocument, myPage){
             var myWidth = myDocument.documentPreferences.pageWidth;
             var myHeight = myDocument.documentPreferences.pageHeight;
             var myX1 = myPage.marginPreferences.left;
             var myY1 = myPage.marginPreferences.top;
             var myX2 = myWidth - myPage.marginPreferences.right;
             var myY2 = myHeight - myPage.marginPreferences.bottom;
             return [myY1, myX1, myY2, myX2];
    // Test, Add return character after every XML Element
    mainTest();
    function mainTest(){
         if (app.documents.length != 0){
             var myDocument = app.documents.item(0);
             //This rule set contains a single rule.
             var myRuleSet = new Array (new AddReturns);
             with(myDocument){
                 var elements = xmlElements;
                 __processRuleSet(elements.item(0), myRuleSet);
         else{
             alert("No open document");
             //Adds a return character at the end of every XML element.
             function AddReturns(){
                 this.name = "AddReturns";
                 //XPath will match on every XML element in the XML structure.
                 this.xpath = "//*";
                 // Define the apply function.
                 this.apply = function(myElement, myRuleProcessor){
                     with(myElement){
                         //Add a return character after the end of the XML element
                         //(this means that the return does not become part of the
                         //XML element data, but becomes text data associated with the
                         //parent XML element).
                         insertTextAsContent("\r", XMLElementPosition.afterElement);
                         //To add the return at the end of the element, use:
                         //insertTextAsContent("\r", XMLElementPosition.afterElement);
                 return true;// Succeeded
             } //End of apply function
    Do you have any ideas?
    Kind regards,
    mannyk

  • Import xml/xsl using javascript

    I had problem in import a xml file with xsl using javascript. CS3 only take the elements in xml without any xsl information when I defined doc.xmlImportPreferences.transformFilename="c:\\sample.xsl"; What else do I need to define to allow CS3 know that my xsl file is sample.xsl.

    By the way, after I maunually import them, it can be handled by the program. I wonder there must be something missing when I try to import it viw Javascript at first time.

Maybe you are looking for