Page 1 of 1

Find and replace

PostPosted: Thu Mar 01, 2012 10:42 pm
by cheopz
Hi,

i started using docxj4 for some project and worked out very well.
Now i got some problem with finding certain placeholder in a document and replacing them.
This might be rather related to JAXB and Xpath but maybe someone can help.

I got some placeholder looking like this {PLACEHOLDER1}, {PLACEHOLDER2}, ... in a predefined document.
When trying to find and replace the placeholder can find all except the first one.
I tried to copy the content from the document to another and it worked.
Any idea what might cause the problem?

Thx for help!

Code: Select all
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
      
   // Replacing place holders with text only values
   MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
   org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart.getJaxbElement();

        String xpath = "//w:r[w:t[contains(text(), concat('{','PLACEHOLDER1', '}'))]]";
   
      
        System.out.println("XPATH " + xpath);
        List<Object> list = documentPart.getJAXBNodesViaXPath(xpath, true);


        for(Object obj : list){
            List<Object>  objContent=((R)obj).getContent();
            objContent.clear();   
            objContent.add(getFindingText());
         }
        wordMLPackage.save(new File("test.docx"));


Code: Select all
private static P getFindingText(){
         org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
         org.docx4j.wml.P  p = factory.createP();
         org.docx4j.wml.Text  t = factory.createText();
         t.setValue("String found");
         org.docx4j.wml.R  run = factory.createR();
         run.getContent().add(t);
         p.getContent().add(run);
         return p;
}

Re: Find and replace

PostPosted: Thu Mar 01, 2012 11:04 pm
by cheopz
Sorry,

dont know what caused but the problem is solved.
Loaded a new (but exact identicial) copy of the predefined document and now everything seems to work.

Re: Find and replace

PostPosted: Fri Mar 02, 2012 11:07 am
by jason
In your Word docx, your run " {PLACEHOLDER1}" was probably split across multiple w:t elements, because of spelling/grammar proofing, or rsIds. Your XPath expression then wouldn't match.