How to remove only the math node using java

Hi Team ,

Below have attached the paragraph , which has math node .My requirement is to remove the math node and replace it as eq1 , eq2 and so on . below is the source code i used .

source code :

if (aNode.getNodeType() == NodeType.SHAPE || aNode.getNodeType() == NodeType.OFFICE_MATH) {
    equCount += 1;
    parastr = parastr.append("eq").append(equCount);
}

It replacing the equation as eq1 but getting some error while processing through my project . below i have mentioned some scenarios for your understanding .

scenario : when the math node removed , it automatically removing the space between the equation and next word like below .i don’t need to remove the space just need to replace the equation as eq

input paragraph : where, “y” is a vector
current output : where, eq1is a vector of
expected output: where, eq1 is a vector of

so to overcome this ,i added extra space like below but it not ressloved and got the below error .
source : parastr = parastr.append(“eq”).append(equCount).append(" ");

scenario 1: (is working fine when there is a word next to equation )
input paragraph : where, “y” is a vector
current output : where, eq1 is a vector of
expected output: where, eq1 is a vector of

scenario 2: (when there is symbol like , ; next to the equation it is providing the extra space in between equation and symbols.)

input paragraph : animal “i”; “X” and “Z” are incidence
current output : animal eq1 ; eq2 and eq3 are incidence
expected output: animal eq1; eq2 and eq3 are incidence

input document : equation reference.docx (12.4 KB)

Please help me to resolve the above error and please do share the source code if possible .

Regards,
Pavithra.

@pavithrasudhakaran You can use code like the following to achieve what you need:

Document doc = new Document("C:\\Temp\\in.docx");

Iterable<OfficeMath> maths = doc.getChildNodes(NodeType.OFFICE_MATH, true);
int counter = 0;
for (OfficeMath math: maths)
{
    if (math.getParentNode().getNodeType() != NodeType.OFFICE_MATH)
    {
        Run replacement = new Run(doc, "eq" + counter);
        counter++;
        math.getParentNode().insertAfter(replacement, math);
        math.remove();
    }
}

doc.save("C:\\Temp\\out.docx");