Home > front end >  looping through Xml elements in indesign extendscript
looping through Xml elements in indesign extendscript

Time:06-13

I'm working on reading an xml via indesign script and create text boxes. Given this xml:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <project name="IPS300980XX_NEW" pagecount="50">
        <styles>
            <style nome="xxx" font="Arial" fontsize="10" bold="2" center="2" />
            <style nome="yyy" font="Times" fontsize="24" bold="1" center="1" />
            <style nome="zzzz" font="Helvetica" fontsize="22" bold="2" center="1" />
        </styles>
    </project>
</root>

I'm trying to loop through "style" nodes, without success. the code I'm using is the following (but i tried with several combinations of xmlelements, children, items, whatever :-( with no success).

"myxml" is the just opened xml document. Every variable has the expected values except "getTheStyle" (and consequently "test").

function creastili(){
        var styles = myxml.project.styles;
        var list = styles.child("style");
        var getTheStyle = "";
    for(var i = 0; i < list.length(); i  ){
        getTheStyle = list[i];
        test = getTheStyle.toString();
        //getTheStyle is always empty.
        }
}

Any help would be really appreciated! Thank you very much.

CodePudding user response:

Perhaps you have to use toXMLString() instead of toString().

This code works for me:

var xml = '''<?xml version="1.0" encoding="UTF-8"?>
<root>
    <project name="IPS300980XX_NEW" pagecount="50">
        <styles>
            <style nome="xxx" font="Arial" fontsize="10" bold="2" center="2" />
            <style nome="yyy" font="Times" fontsize="24" bold="1" center="1" />
            <style nome="zzzz" font="Helvetica" fontsize="22" bold="2" center="1" />
        </styles>
    </project>
</root>''';


function creastili(xml) {
    var root = new XML(xml); // native Extendscript XML parser
    var list = root.project.styles.children();
    for(var i = 0; i < list.length(); i  ){
        var getTheStyle = list[i];
        var test = getTheStyle.toXMLString();
        alert(test);
    }
}

creastili(xml);

enter image description here

You can get attributes of a 'style' this way:

var root = new XML(xml);
var style = root.project.styles.children()[0];
var name = style.@nome;
var font = style.@font;
var size = style.@fontsize;
// etc

alert([name, font, size].join('\n'));
  • Related