Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

Read XML file with JSX

New Here ,
Dec 29, 2011 Dec 29, 2011

I would like to be able to read an XML file in an InDesign script and create a new document by looping through its nodes and extracting content from them. I've never done this before and I can't seem to find the right information on how to do it. Can someone give me a snippet to get me started? Thanks!

TOPICS
Scripting
10.7K
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Valorous Hero , Dec 30, 2011 Dec 30, 2011

Read the "Integrating XML into JavaScript" chapter in "JavaScript Tools Guide".

Below is a script I made a while ago. It can give you idea how to start writing your own script. It reads an xml-file, creates a new document from the template, relinks links listed in the xml-file comparing the width, height and resolution with data in the xml-file.

// Copyright 2011, «Студия Форма»

// October 3, 2011

// Written by Kasyan Servetsky

// http://www.kasyan.ho.com.ua

// e-mail: askoldich@yahoo.com

//=========

...
Translate
Valorous Hero ,
Dec 30, 2011 Dec 30, 2011

Read the "Integrating XML into JavaScript" chapter in "JavaScript Tools Guide".

Below is a script I made a while ago. It can give you idea how to start writing your own script. It reads an xml-file, creates a new document from the template, relinks links listed in the xml-file comparing the width, height and resolution with data in the xml-file.

// Copyright 2011, «Студия Форма»

// October 3, 2011

// Written by Kasyan Servetsky

// http://www.kasyan.ho.com.ua

// e-mail: askoldich@yahoo.com

//==================================== GLOBALS ==========================================

var gErrMsgArr = [];

//=======================================================================================

Main();

//=================================== FUNCTIONS  =========================================

function Main() {

    var montage, doc, docFile, component, noErrors, pdfPath, pdfFile, targetPagesLength, destinationFolder;

    var currentFolder = Folder.selectDialog("Выберите текущую папку");  //new Folder("/D/Evgen/");

    if (currentFolder == null) exit();

    var currentFolderPath = currentFolder.absoluteURI + "/";

   

    var xmlFile = new File(currentFolderPath + "!sforder.xml");

    if (!xmlFile.exists) exit();   

    var outFolderPath = "~/Desktop/Output/";

    var outFolder = new Folder(outFolderPath);

    if (!outFolder.exists) outFolder.create();

    xmlFile.open("r");

    var xmlStr = xmlFile.read();

    xmlFile.close();

    var root = new XML(xmlStr);

    default xml namespace = "http://www.forma-studio.com/order";

    var linksArr = [];

    var componentList = root.xpath("/order/product/components/component");

    var componentsLength = componentList.length();   

    for (var c = 0; c < componentsLength; c++) {

        component = componentList;

        linksArr.push({ name : component.images.image.file_name.toString(),

                            width : parseInt(component.images.image.size.width),

                            height : parseInt(component.images.image.size.height),

                            resolution : parseInt(component.images.image.resolution),

                           });

    }

    var montageList = root.xpath("/order/product/montages/montage");

    var montagesLength = montageList.length();

    for (var i = 0; i < montagesLength; i++) {

        montage = montageList;

   

        app.scriptPreferences.userInteractionLevel = UserInteractionLevels.neverInteract;       

        app.open(new File(montage.layout_filename));

        doc = app.activeDocument;

        docFile = new File(outFolderPath + montage.result_filename + ".indd");

        doc.save(docFile);

        app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;

       

        targetPagesLength = parseInt(montage.page_count);

        if (!isNaN(targetPagesLength)) {

            //$.writeln("About to remove pages - " + doc.name + " - " + montage.page_count);

            while (doc.pages.length > targetPagesLength) {

                doc.pages.lastItem().remove();

            }

        }

   

        UpdateAllOutdatedLinks(doc);

       

        noErrors = ProcessDoc(doc, linksArr, currentFolderPath);

        if (noErrors) {

            destinationFolder = new Folder(montage.destination);

            VerifyFolder(destinationFolder);

            pdfPath = montage.destination + "/" + montage.result_filename + ".pdf"

            pdfFile = new File(pdfPath);

            doc.exportFile(ExportFormat.PDF_TYPE, pdfFile, false, "[High Quality Print]");

        }       

        doc.close(SaveOptions.YES);

    }

}

//--------------------------------------------------------------------------------------------------------------------------------------------------------

function ProcessDoc(doc, linksArr, currentFolderPath) {

    var link, linkFile;

    var noErrors = true;

    var links = doc.links;

//~     $.writeln("--------------------------");

//~     $.writeln(doc.name);

    for (var i = links.length-1; i >= 0; i--) {

        link = doc.links;

        for (var o = 0; o < linksArr.length; o++) {

            if (link.name == linksArr.name) {

                linkFile = new File(currentFolderPath + linksArr.name);

                if (linkFile.exists) {

//~                     $.writeln("\t" + o + " - " + linkFile.name + " - linkFile.exists");

                    if (CheckLink(link, linksArr, doc) == false) noErrors = false;

                    link.relink(linkFile);

                }

                else {

                    $.writeln(o + " - " + linkFile.name + " - linkFile doesn't exist");

                    noErrors = false;

                }

            }

        }

    }

//~     $.writeln("--------------------------");

   

    return noErrors;

}

//--------------------------------------------------------------------------------------------------------------------------------------------------------

function CheckLink(link, linkObj, doc) {

    var errMessage;   

    var result = true;

    var image = link.parent;

    var actualPpi = image.actualPpi;

    var md = link.linkXmp;

    var reportFilePath = doc.fullName.absoluteURI.replace(/\.indd$/i, ".txt");

    var width = parseInt(md.getProperty("http://ns.adobe.com/exif/1.0/", "exif:PixelXDimension"));

    var height = parseInt(md.getProperty("http://ns.adobe.com/exif/1.0/", "exif:PixelYDimension"));

   

    if (actualPpi[0] != linkObj.resolution && actualPpi[1] != linkObj.resolution) {

        errMessage = link.name + " - resolution is NOT correct: " + actualPpi[0] + "/" + actualPpi[1] + " ppi instead of " + linkObj.resolution + "\r";

        if (IsInArray(errMessage, gErrMsgArr) == false) {

            gErrMsgArr.push(errMessage);           

            //$.writeln(errMessage);

            WriteToFile(errMessage, reportFilePath);

            result = false;   

        }   

    }

    if (height != linkObj.height) {

        errMessage = link.name + " - height is NOT correct: " + height + " pixels instead of " + linkObj.height + "\r";

        if (IsInArray(errMessage, gErrMsgArr) == false) {

            gErrMsgArr.push(errMessage);           

            //$.writeln(errMessage);

            WriteToFile(errMessage, reportFilePath);

            result = false;   

        }       

    }

    if (width != linkObj.width) {

        errMessage = link.name + " - width is NOT correct: " + width + " pixels instead of " + linkObj.width + "\r";

        if (IsInArray(errMessage, gErrMsgArr) == false) {

            gErrMsgArr.push(errMessage);           

            //$.writeln(errMessage);

            WriteToFile(errMessage, reportFilePath);

            result = false;   

        }

    }

    return result;

}

//--------------------------------------------------------------------------------------------------------------------------------------------------------

function UpdateAllOutdatedLinks(doc) {

    var link;

    for (var i = doc.links.length-1; i >= 0; i--) {

        link = doc.links;

        if (link.status == LinkStatus.LINK_OUT_OF_DATE) link.update();

    }

}

//--------------------------------------------------------------------------------------------------------------------------------------------------------

function WriteToFile(text, reportFilePath) {

    file = new File(reportFilePath);

    file.encoding = "UTF-8";

    if (file.exists) {

        file.open("e");

        file.seek(0, 2);

    }

    else {

        file.open("w");

    }

    file.write(text);

    file.close();

}

//--------------------------------------------------------------------------------------------------------------------------------------------------------

function GetDate() {

    var date = new Date();

    if ((date.getYear() - 100) < 10) {

        var year = "0" + new String((date.getYear() - 100));

    }

    else {

        var year = new String((date.getYear() - 100));

    }

    var dateString = (date.getMonth() + 1) + "/" + date.getDate() + "/" + year + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

    return dateString;

}

//--------------------------------------------------------------------------------------------------------------------------------------------------------

function ErrorExit(error, icon) {

    alert(error, gScriptName + " - " + gScriptVersion, icon);

    exit();

}

//--------------------------------------------------------------------------------------------------------------------------------------------------------

function IsInArray(string, arr) {

    for (x in arr) {

        if (string.toLowerCase() == arr.toLowerCase()) {

            return true;

        }

    }

    return false;

}

//--------------------------------------------------------------------------------------------------------------------------------------------------------

function VerifyFolder(folder) {

    if (!folder.exists) {

        var folder = new Folder(folder.absoluteURI);

        var arr1 = new Array();

        while (!folder.exists) {

            arr1.push(folder);

            folder = new Folder(folder.path);

        }

        var arr2 = new Array();

        while (arr1.length > 0) {

            folder = arr1.pop();

            if (folder.create()) {

                arr2.push(folder);

            } else {

                while (arr2.length > 0) {

                    arr2.pop.remove();

                }

                throw "Folder creation failed";

            }

        }

    }

}

//--------------------------------------------------------------------------------------------------------------------------------------------------------

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
New Here ,
Dec 30, 2011 Dec 30, 2011
LATEST

That looks very helpful. Thanks very much!

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines