Page 1 of 1

modifying text content via API

Posted: Thu Nov 17, 2011 10:54 pm
by TimWallace
I have a client who wants custom operations to edit certain content types (I have actions that build windows to maintain certain types of data that is part of the document). I have run into a problem being able to replace the text content of various AuthorNodes. I have no problem setting attributes, but I cannot figure out a way to set the contents of the text content that is contained within an element. Can someone please point me in the right direction?

Re: modifying text content via API

Posted: Fri Nov 18, 2011 3:18 pm
by mihaela
Hi Tim,

To change the content of the AuthorNodes you can use the AuthorDocumentController, which provides methods for modifying the Author document:

Code: Select all

AuthorDocumentController controller = authorAccess.getDocumentController();
To replace the text content of a node you can first delete this content by using the following method:

Code: Select all

controller.delete(startOffset, endOffset); 
and then you can insert the new text content:

Code: Select all

controller.insertText(offset, text);
The offsets parameters represent positions in the Author document.
The following image presents an Author document fragment. The red markers indicate special control characters which are used to point to the start and the end offsets of the fragment containing nodes.
Image
To find the start and end offsets of a node, use the

Code: Select all

int getStartOffset();
and

Code: Select all

int getEndOffset();
methods from the AuthorNode.

Another approach is to iterate through all the text content intervals and replace the ones that you want to modify. Here is an example:

Code: Select all

    AuthorDocumentController documentController = authorAccess.getDocumentController();

TextContentIterator iterator = documentController.getTextContentIterator(startOffset, endOffset);
try {
documentController.beginCompoundEdit();
// Iterate through text content intervals
while (iterator.hasNext()) {
TextContext next = iterator.next();
//Check first if this text can be edited
if (next.getEditableState() == TextContext.EDITABLE
|| next.getEditableState() == TextContext.EDITABLE_IN_FILTERED_CONDITIONAL_PROFILING) {
CharSequence textSequence = next.getText();
if (textSequence != null) {
String text = textSequence.toString();
if (text.contains("toReplace")) {
// Replace the modified string
next.replaceText(text.replaceAll("toReplace", "newText"));
}
}
}
}
} finally {
documentController.endCompoundEdit();
}

Regards,
Mihaela
---
Mihaela Calotescu
<oXygen/> XML Editor, Schema Editor and XSLT Editor/Debugger
http://www.oxygenxml.com