【问题标题】:Access XML Attribute Names in Extendscript在 Extendscript 中访问 XML 属性名称
【发布时间】:2015-05-26 11:58:53
【问题描述】:

我正在尝试在extendscript 中解析一个xml 对象,尤其是处理属性。我知道我可以通过

访问xml属性
xmlObj.@attributename

xmlObj.attributes()

返回所有属性的列表,但我还需要属性名称而不仅仅是值。反正有没有像关联数组/对象的名称和值?

(我为 Illustrator CS6 使用扩展脚本)

谢谢你, 阿诺

【问题讨论】:

    标签: javascript xml attributes adobe-illustrator extendscript


    【解决方案1】:

    下面的代码应该可以帮助您。还可以查看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();
    

    【讨论】:

    • 谢谢,很遗憾我忘了说我使用的是Extendscript for Illustrator (cs6),这个脚本只能在inDesign 中工作。有没有办法用插画家 XML Class 来处理?
    • 没问题。我环顾四周,但没有找到任何好的解决方案。我认为这可以通过使用 xPath 表达式来完成。
    • 我用 xpaths 试过了,但不知何故,它们在扩展脚本中不起作用。 name(//element/@*[1]) 适用于任何 xpath 评估器,但在扩展脚本中它不返回任何内容
    • 很奇怪不是吗?也许您在 Adob​​e 论坛上提问。我仍然会选择InDesign Scripting forum。他们是最活跃的,经常要处理xml
    【解决方案2】:

    我找到了用正则表达式解决它的方法

    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;
    }

    我仍然使用 Extendscripts/Illustrators xml-class 解析 xml,然后手动提取属性

    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]);
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多