title: docx4j find and replace
body: <p>I have docx document with some placeholders. Now I should replace them with other content and save new docx document. I started with <a href="http://htmlpreview.github.io/?https://github.com/plutext/docx4j/blob/master/docs/Docx4j_GettingStarted.html" rel="nofollow">docx4j</a> and found this method:</p>
  
  <pre><code>public static List&lt;Object&gt; getAllElementFromObject(Object obj, Class&lt;?&gt; toSearch) {
      List&lt;Object&gt; result = new ArrayList&lt;Object&gt;();
      if (obj instanceof JAXBElement) obj = ((JAXBElement&lt;?&gt;) obj).getValue();
  
      if (obj.getClass().equals(toSearch))
          result.add(obj);
      else if (obj instanceof ContentAccessor) {
          List&lt;?&gt; children = ((ContentAccessor) obj).getContent();
          for (Object child : children) {
              result.addAll(getAllElementFromObject(child, toSearch));
          }
      }
      return result;
  }
  
  public static void findAndReplace(WordprocessingMLPackage doc, String toFind, String replacer){
      List&lt;Object&gt; paragraphs = getAllElementFromObject(doc.getMainDocumentPart(), P.class);
      for(Object par : paragraphs){
          P p = (P) par;
          List&lt;Object&gt; texts = getAllElementFromObject(p, Text.class);
          for(Object text : texts){
              Text t = (Text)text;
              if(t.getValue().contains(toFind)){
                  t.setValue(t.getValue().replace(toFind, replacer));
              }
          }
      }
  }
  </code></pre>
  
  <p>But that only work rarely because usually the placeholders splits across multiple texts runs.</p>
  
  <p>I tried <a href="http://www.docx4java.org/trac/docx4j/browser/trunk/docx4j/src/main/java/org/docx4j/samples/UnmarshallFromTemplate.java" rel="nofollow">UnmarshallFromTemplate</a> but it work rarely too.</p>
  
  <p>How this problem could be solved?</p>