3 Replies Latest reply on Sep 17, 2014 9:46 PM by JulianFT

    Check for existing XML element


      Dear all,


      I'm trying to write a simple script first checking to see whether an XML element exists, and then creating it if it doesn't. I've tried editing a piece of code that I used previously to do the same for paragraph styles, but apparently it's not that straightforward. Currently, all I get is the error "Cannot execute the script in target engine 'main'!" Without the checking, adding the XML element based on the search result works fine.


      /* Find all instances of the word "Superscript" */
      app.findTextPreferences.findWhat = "Superscript";
      var mySuperscript = myDocument.findText(); // Save search result for future reference
      /* See if an XML element named "Superscript" already exists, and create it if that's not the case; then add it to all instances of the word "Superscript" */
      var myXMLElementSuper = myDocument.xmlElements.item("Superscript");
      try {
      var myName = myXMLElementSuper.name;
      catch (myError){
          var myXMLElementSuper = myDocument.xmlElements.add({markupTag:"Superscript", xmlContent:mySuperscript[i]});}


      Any assistance would be greatly appreciated!


      Kind regards and thanks in advance,



        • 1. Re: Check for existing XML element
          Dirk Becker Level 4

          The myDocument.xmlElements always has a single element - the root element.

          If you want your element straight below that, you have to work one level down.

          Using try-catch for such regular situations is bad as you then typically switch off the ESTK option to break on exceptions and miss the real problems. Use the isValid property instead.


          var rootXE = myDocument.xmlElements.item(0);
          var superXE = rootXE.xmlElements.itemByName("Superscript");
          if( !superXE.isValid )
            superXE = rootXE.xmlElements.add(...
           superXE = superXE.getElements()[0]; // take first of potentially multiple elements
          • 2. Re: Check for existing XML element
            Sajeev Sridharan Level 4

            Try this,


            app.findTextPreferences.findWhat = "Superscript";  
            var mySuperscript = app.activeDocument.findText();
            for(var i=0; i< mySuperscript.length; i++)
                if(mySuperscript[i].associatedXMLElements[0].markupTag.name != "Superscript")
                    app.activeDocument.xmlElements[0].xmlElements.add({markupTag:"Superscript", xmlContent:mySuperscript[i]});  




            • 3. Re: Check for existing XML element
              JulianFT Level 1

              Dear Dirk and Vandy,


              thank you so much for your kind help. Both solutions work perfectly.


              Kind regards,