Replace problem with partial matching segments

Problem:I am reading contents from Xml file Xml file consist of Two Tags (source and translation). I want to replace content in source tage with contents in translation tag..
the problem is that it replace partial matching segments. eg
Xml file Consist of following two Segments
1) I am here
2) I am here in office
now i just want to replace segment 1 (I am here) with replacement (This is testing Translation) and does not want to replace segment two (I am here in office), the api (aspose word for java) replace first segment with (this is testing Translation) and second with (this is testing Translation in office i do not want to replace i am here in office) . I want to replace exact match like(I am here) with (test) not to replace partial matching (I am here in
Here below is my sample code..
String MyDir = "C:/Users/Sath Tech/Desktop/";
String fileContents = "";
String Xmlpath = MyDir;
try
{
License license = new License();
license.setLicense("E:/Projects/Aspose.Total.Java.lic");
Document doc = new Document(MyDir + "bug.docx");
File fXmlFile = new File(Xmlpath + "/"+"bug.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
org.w3c.dom.Document doc1 = dBuilder.parse(fXmlFile);
doc1.getDocumentElement().normalize();
NodeList nList = doc1.getElementsByTagName("segments");
String source = "", translation = "";
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
source = eElement.getElementsByTagName("source").item(0).getTextContent();
System.out.println(source);
translation = eElement.getElementsByTagName("translation").item(0).getTextContent();
doc.getRange().replace(source.trim(), translation, false, false);
}
}
doc.save(MyDir + "Out.docx");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

Im waiting for you kind reply

Hi Hashmat,

Thanks for your inquiry. You are facing the expected behavior of Aspose.Words. If the source (text) appears multiple times in your document, I suggest you following solution.

1) Filter the source (text) which is bigger in length e.g I am here in office’ has greater length than ‘I am here’.
2) Call the Range.Replace method for that source (text) which has greater length.

Please check following code example. Hope this helps you.

Document doc = new Document(MyDir + "bug.docx");

doc.getRange().replace("I am here in office", "This is testing Translation",true, true);

doc.getRange().replace("I am here", "This is testing Translation",true, true);

doc.save(MyDir + "Out.docx");