arnoson
arnoson

Reputation: 53

Access XML Attribute Names in Extendscript

I'm trying to parse an xml Object in extendscript and especially deal with the Attributes. I know i can access xml attributes by

xmlObj.@attributename

and

xmlObj.attributes()

returns a list of all attributes, but I also need the attribute names not just the values. Is there anyway to get something like and associative array/object with names and values?

(I use extendscript for illustrator CS6)

thank you, arno

Upvotes: 1

Views: 3930

Answers (2)

arnoson
arnoson

Reputation: 53

i've found a way solve it with regular Expressions

function getAttributes(xml_node_str) {
  // select the start tag <elem >
  var reg_exp = /<[^>]*>/;
  var start_tag_str = reg_exp.exec(xml_node_str);

  // extract the attributes
  reg_exp = /[^"\s]*="[^"]*"/g;
  var result;
  var attributes = [];

  while ((result = reg_exp.exec(start_tag_str)) !== null) {
    // the attribute (name="value")
    var attr = result[0];
    // array containing name and "value"
    var attr_arr = attr.split('=');
    // delete the "'s
    attr_arr[1] = attr_arr[1].substr(1, attr_arr[1].length - 2);

    attributes.push(attr_arr);
  }
  return attributes;
}

I still parse the xml with Extendscripts/Illustrators xml-class and then extract the attributes manually

var xml = <root><obj a1="01" a2="02" ></obj></root > ;

var attributes = getAttributes(xml.obj.toXMLString());

for (var i = 0; i < attributes.length; i++) {
  alert(attributes[i][0] + ' -> ' + attributes[i][1]);
}

Upvotes: 0

fabianmoronzirfas
fabianmoronzirfas

Reputation: 4131

The code below should get you going. Take also a look into the XMLElement Object.

var main = function() {
  // create some xml and write it to file
  var root = new XML("<root/>");
  var child = new XML("<child/>");
  child.@string = "Hello Attribute"; // jshint ignore:line
  child.@num = 23; // jshint ignore:line
  root.appendChild(child);
  var file = new File("~/Desktop/test.xml");
  var xml = root.toXMLString();
  file.open("W");
  file.write(xml);
  file.close();

  // get the current doc
  var doc = app.activeDocument;
  // import the xml
  doc.importXML(file);
  // get the elements
  var xmlroot = doc.xmlElements[0];
  var xmlchild = xmlroot.xmlElements[0];
  // loop all attributes of element "child"
  // and write them into the console
  for (var i = 0; i < xmlchild.xmlAttributes.length; i++) {
    var attr = xmlchild.xmlAttributes[i];
    $.writeln(attr.name);
  }
};
main();

Upvotes: 2

Related Questions