3 Replies Latest reply on Oct 14, 2008 8:17 PM by (Gary_Vidal)

    Iterate through xml elements vb cs2

    Dave Pepper
      Does anyone know how to iterate through xml elements without xml rules (unfortunately I have to do this project with cs2). I've heard it's hard and slow to iterate through each element in cs2.
        • 1. Re: Iterate through xml elements vb cs2
          Level 1
          Hi David,

          It's not hard, it's just slow. Iterate just as you would iterate through any set of objects in a collection:

          Rem Given an XMLElement "myXMLElement"
          For myCounter = 1 to myXMLElement.XMLElements.Count
          Set myChildXMLElement = myXMLElement.XMLElements.Item(myCounter)
          Rem Do something with myChildXMLElement
          Next

          The only trick is that you often need to use recursive iteration--if the child element has elements you need to search, for example. It can also be tricky in that you need to avoid deleting or changing the parent element of an element that you're working on, or deleting or adding elements before a given element.

          Thanks,

          Ole
          • 2. Re: Iterate through xml elements vb cs2
            Dave Pepper Level 1
            Ole, I'm running into a problem with iterating through child xml elements. Could you give me an example of how to use recursive iteration to go through each element. My project does not need to delete or move the elements, it merely looks at the attributes and contents of each element.
            • 3. Re: Iterate through xml elements vb cs2
              Here is a script I find useful. It recursively iterates over indesign xml structure and invokes a function on each node.

              HTH,
              =========================================================
              function invokeFunctionOnNode(parentNode, func) {
              var pNode = parentNode;
              //Call on Parent Node
              func(pNode);
              var elementCount = 0;
              try{
              elementCount = pNode.xmlElements.length;
              }catch(ex){}
              if (elementCount > 0) {
              var ctr = 0;
              for (var elem = 0 ; elem < elementCount; elem++) {
              var currentNode = pNode.xmlElements.item(elem);
              func(currentNode);
              try {
              if (currentNode.xmlElements.length > 0) {
              invokeFunctionOnNode(currentNode, func) ;
              }
              } catch(ex) {}
              }
              }