Search code examples
javascriptxmladobe-indesignextendscript

Linking XML elements to page items in InDesign


I can check the XML of selected text like this:

app.selection[0].associatedXMLElements[0];

But in my research, I am still left scratching my head about how to do the most basic thing with XML using script: how do I assign XML to items? I can manually do this by opening the structure pane, then dragging the element over the desired frame on the page. If it's possible the old fashioned way, I imagine it's possible with script.

  • How do I link an existing XML element to an existing page item?

  • The above code only seems to work on selected text. If I select a graphic, it won't run.
    How can I link XML to a selected graphic?


Solution

  • You can reference your xml node and your text frame and use placeXML

        myXMl = myDoc.xmlElements[0];
    
        var myXmlNode = myXMl.evaluateXPathExpression("/myXML/node1")[0];
    
        var myFrame =  app.activeDocument.pages[0].textFrames[0];
    
        myXmlNode.placeXML(myFrame);
    

    The advantage of this approach is that any aid:pstyle or aid:cstyle will be linked to existing matching style automaticaly

    The alternative is to select the value of the node as text and place it into the text frame at insertion point:

     myXMl = myDoc.xmlElements[0];
    
     var myText = myXMl.xpath("/myXML/node1[1]/text()");
    
     var myFrame =  app.activeDocument.pages[0].textFrames[0];
    
     myFrame.parentStory.insertionPoints[-1].contents = myText + '\r';