Pages: 1
Print
Author Topic: Getting all the text children of an element in a script  (Read 3238 times)
dcramer
Member

Posts: 120


« on: March 15, 2010, 11:39:30 AM »

Using XMetaL 4.6 (but upgrading soon). I'm writing a script that will iterate through elements that have titles but no id attributes and present the user with a dialog showing the title and a suggested id based on that title (with spaces and weird characters removed). The user can change the id or skip this one. It's all easy enough except getting the text of the title elements. The <title> might have inline markup, but what I want are all the text() children of the title:

I've tried the following, but titleText.lenght is always 0. 

Code:
needIds = ActiveDocument.getNodesByXPath("//*[not(@id) and ./title]");
titles = ActiveDocument.getNodesByXPath("//*[not(@id) and ./title]/title");

for (var i=0; i < needIds.length; i++){
needsId = needIds.item(i);
title = titles.item(i);

titleText = title.getNodesByXPath(".//text()");

Application.Alert("titleText=" + titleText.length);

}

Basically, I want to get what I would get using <xsl:value-of select="normalize-space(title)"/> for a given title element.

Thanks,
David
Logged

David Cramer
Technical Writer
Motive, an Alcatel-Lucent Company
dcramer
Member

Posts: 120


« Reply #1 on: March 15, 2010, 02:43:45 PM »

Ok, I figured it out. Have to use a tree walker:

Code:
function readtree(node) {
// Read the DOM tree
// Do if this is a DOMText node
if (node.nodeType==3) {
titleText += node.data;
}

// Process this node's children
if (node.hasChildNodes()) {
readtree(node.firstChild);
}

// Continue with this node's siblings
if (node.nextSibling != null) {
readtree(node.nextSibling)
}
}
Logged

David Cramer
Technical Writer
Motive, an Alcatel-Lucent Company
Pages: 1
Print
Jump to: