Updae the value of a SdtType.PLAIN_TEXT

Hello,

I read a simple DOCXfile and I want to change the value of a Plain Text field with Aspose.Words.
The section of the sample word document is as follows:
# Inserting text

This value is templated and will be edited through Aspose: my value is here

The value with the same id is also here : my value is here

This text here should have its font set programmatically to “Century Gothic” : text with century gothic

## How-to

Select the field you with to template, in design mode, and click “Plain Text Content Control”. Then change its properties and define a title/tag

The code I use is the following:

for (Object control : doc.getChildNodes(NodeType.STRUCTURED_DOCUMENT_TAG, true))
{
    StructuredDocumentTag sdt = (StructuredDocumentTag)control;
    builder.writeln("Standard Type " + SdtType.getName(sdt.getSdtType()) + " - " + sdt.getPlaceholderName() + " - " + sdt.getTitle());

    if (sdt.getTitle().equals("title_cb_1") || sdt.getTitle().equals("title_cb_3"))
    {
        sdt.setChecked(true);
    }
    else if (sdt.getTitle().equals("title_textfield"))
    {
        if (sdt.getSdtType() == SdtType.PLAIN_TEXT)
        {
            //sdt.getNodeType()  --> STRUCTURED_DOCUMENT_TAG
            sdt.removeAllChildren();
            Paragraph para = new Paragraph(doc);
            Run run = new Run(doc);
            run.setText("Set A New Value in place of the default");
            para.appendChild(run);
            sdt.appendChild(para); // Here it throws error 
        }
    }
}

However, an ERROR is thrown:
java.lang.IllegalArgumentException: Cannot insert a node of this type at this location.

I find this solution overengineered for such a trivial task, so please can you suggest a better way of doing updates like those?

@Zdimitris Most likely, the problem occurs because SDT is on inline markup level, but in the code a block level node (paragraph) is inserted into it. Please try modifying your code like this:

if (sdt.getSdtType() == SdtType.PLAIN_TEXT)
{
    sdt.removeAllChildren();
    Run run = new Run(doc);
    run.setText("Set A New Value in place of the default");
    if (sdt.getLevel() == MarkupLevel.INLINE)
    {
        sdt.appendChild(run);
    }
    else if (sdt.getLevel() == MarkupLevel.BLOCK)
    {
        Paragraph para = new Paragraph(doc);
        para.appendChild(run);
        sdt.appendChild(para); 
    }
}
1 Like

Thank you @alexey.noskov for your prompt reply.
Your solution works fine.

1 Like