A simple way to read track changes from a docx document is to navigate xpath and manage the result.
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File("myFile.docx")); MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart(); List<?> revisionInsList = mainDocumentPart.getJAXBNodesViaXPath("//w:ins", true); for (Object obj : revisionInsList) { System.out.println("--------------INSERT----------"); RunIns ins = (org.docx4j.wml.RunIns) obj; System.out.println("Author:" + ins.getAuthor()); System.out.println("id(position):" + ins.getId()); System.out.println("Date:" + ins.getDate()); List<Object> listR = ins.getCustomXmlOrSmartTagOrSdt(); for (Object aListR : listR) { R r = ((R) aListR); printRevision(r); } } List<?> revisionDelList = mainDocumentPart.getJAXBNodesViaXPath("//w:del", false); for (Object obj : revisionDelList) { System.out.println("--------------DELETE----------"); RunDel del = (org.docx4j.wml.RunDel) obj; System.out.println("Author:" + del.getAuthor()); System.out.println("id(position):" + del.getId()); System.out.println("Date:" + del.getDate()); List<Object> listR = del.getCustomXmlOrSmartTagOrSdt(); for (Object aListR : listR) { R r = ((R) aListR); printRevision(r); } } List<?> revisionDChangeList = mainDocumentPart.getJAXBNodesViaXPath(XPATH_TO_REVISION_FORMAT_CHANGE, false); for (Object obj : revisionDChangeList) { System.out.println("--------------Modify Format----------"); CTRPrChange change = (CTRPrChange)obj; System.out.println("Author:" + change.getAuthor()); System.out.println("id(position):" + change.getId()); System.out.println("Date:" + change.getDate()); }
A simple method to print revision “text” is the following code:
public static void printRevision(R r){ Object objInternal = r.getContent(); if(objInternal instanceof JAXBElement){ System.out.println(((JAXBElement) objInternal).getValue()); } else if (objInternal instanceof ArrayList){ for (int j = 0; j < ((ArrayList) objInternal).size() ; j++) { Object objDeleteInternal = ((ArrayList) objInternal).get(j); if(objDeleteInternal instanceof Text){ System.out.println(((Text)objDeleteInternal).getValue()); } else if(objDeleteInternal instanceof DelText) { System.out.println(((DelText)objDeleteInternal).getValue()); } else { JAXBElement jab = (JAXBElement) ((ArrayList) objInternal).get(j); Text t = (Text)jab.getValue(); System.out.println(t.getValue()); } } } }
Categories: Informatica, JAVA