public abstract class DocumentVisitor
With DocumentVisitor you can define and execute custom operations
that require enumeration over the document tree. For example, Aspose.Words uses DocumentVisitor internally for saving Document
in various formats and for other operations like finding fields or bookmarks over
a fragment of a document. To use DocumentVisitor: DocumentVisitor provides default implementations for all of the VisitXXX methods
to make it easier to create new document visitors as only the methods required for the particular
visitor need to be overridden. It is not necessary to override all of the visitor methods. For more information see the Visitor design pattern. Example:
public void docStructureToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
DocStructurePrinter visitor = new DocStructurePrinter();
// When we get a composite node to accept a document visitor, the visitor visits the accepting node,
// and then traverses all of the node's children in a depth-first manner.
// The visitor can read and modify each visited node.
doc.accept(visitor);
System.out.println(visitor.getText());
}
/// <summary>
/// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string.
/// </summary>
public static class DocStructurePrinter extends DocumentVisitor {
public DocStructurePrinter() {
mAcceptingNodeChildTree = new StringBuilder();
}
public String getText() {
return mAcceptingNodeChildTree.toString();
}
/// <summary>
/// Called when a Document node is encountered.
/// </summary>
public int visitDocumentStart(Document doc) {
int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount();
indentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
mDocTraversalDepth++;
// Allow the visitor to continue visiting other nodes.
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Document node have been visited.
/// </summary>
public int visitDocumentEnd(Document doc) {
mDocTraversalDepth--;
indentAndAppendLine("[Document end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Section node is encountered in the document.
/// </summary>
public int visitSectionStart(final Section section) {
// Get the index of our section within the document
NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false);
int sectionIndex = docSections.indexOf(section);
indentAndAppendLine("[Section start] Section index: " + sectionIndex);
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Section node have been visited.
/// </summary>
public int visitSectionEnd(final Section section) {
mDocTraversalDepth--;
indentAndAppendLine("[Section end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Body node is encountered in the document.
/// </summary>
public int visitBodyStart(final Body body) {
int paragraphCount = body.getParagraphs().getCount();
indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Body node have been visited.
/// </summary>
public int visitBodyEnd(final Body body) {
mDocTraversalDepth--;
indentAndAppendLine("[Body end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Paragraph node is encountered in the document.
/// </summary>
public int visitParagraphStart(final Paragraph paragraph) {
indentAndAppendLine("[Paragraph start]");
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Paragraph node have been visited.
/// </summary>
public int visitParagraphEnd(final Paragraph paragraph) {
mDocTraversalDepth--;
indentAndAppendLine("[Paragraph end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// </summary>
public int visitRun(final Run run) {
indentAndAppendLine("[Run] \"" + run.getText() + "\"");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a SubDocument node is encountered in the document.
/// </summary>
public int visitSubDocument(final SubDocument subDocument) {
indentAndAppendLine("[SubDocument]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
/// </summary>
/// <param name="text"></param>
private void indentAndAppendLine(final String text) {
for (int i = 0; i < mDocTraversalDepth; i++) {
mAcceptingNodeChildTree.append("| ");
}
mAcceptingNodeChildTree.append(text + "\r\n");
}
private int mDocTraversalDepth;
private StringBuilder mAcceptingNodeChildTree;
}
Method Summary | ||
---|---|---|
int | visitAbsolutePositionTab(AbsolutePositionTab tab) | |
Called when a |
||
int | visitBodyEnd(Body body) | |
Called when enumeration of the main text story in a section has ended.
|
||
int | visitBodyStart(Body body) | |
Called when enumeration of the main text story in a section has started.
|
||
int | visitBookmarkEnd(BookmarkEnd bookmarkEnd) | |
Called when an end of a bookmark is encountered in the document.
|
||
int | visitBookmarkStart(BookmarkStart bookmarkStart) | |
Called when a start of a bookmark is encountered in the document.
|
||
int | visitBuildingBlockEnd(BuildingBlock block) | |
Called when enumeration of a building block has ended.
|
||
int | visitBuildingBlockStart(BuildingBlock block) | |
Called when enumeration of a building block has started.
|
||
int | visitCellEnd(Cell cell) | |
Called when enumeration of a table cell has ended.
|
||
int | visitCellStart(Cell cell) | |
Called when enumeration of a table cell has started.
|
||
int | visitCommentEnd(Comment comment) | |
Called when enumeration of a comment text has ended.
|
||
int | visitCommentRangeEnd(CommentRangeEnd commentRangeEnd) | |
Called when the end of a commented range of text is encountered.
|
||
int | visitCommentRangeStart(CommentRangeStart commentRangeStart) | |
Called when the start of a commented range of text is encountered.
|
||
int | visitCommentStart(Comment comment) | |
Called when enumeration of a comment text has started.
|
||
int | visitDocumentEnd(Document doc) | |
Called when enumeration of the document has finished.
|
||
int | visitDocumentStart(Document doc) | |
Called when enumeration of the document has started.
|
||
int | visitEditableRangeEnd(EditableRangeEnd editableRangeEnd) | |
Called when an end of an editable range is encountered in the document.
|
||
int | visitEditableRangeStart(EditableRangeStart editableRangeStart) | |
Called when a start of an editable range is encountered in the document.
|
||
int | visitFieldEnd(FieldEnd fieldEnd) | |
Called when a field ends in the document.
|
||
int | visitFieldSeparator(FieldSeparator fieldSeparator) | |
Called when a field separator is encountered in the document.
|
||
int | visitFieldStart(FieldStart fieldStart) | |
Called when a field starts in the document.
|
||
int | visitFootnoteEnd(Footnote footnote) | |
Called when enumeration of a footnote or endnote text has ended.
|
||
int | visitFootnoteStart(Footnote footnote) | |
Called when enumeration of a footnote or endnote text has started.
|
||
int | visitFormField(FormField formField) | |
Called when a form field is encountered in the document.
|
||
int | visitGlossaryDocumentEnd(GlossaryDocument glossary) | |
Called when enumeration of a glossary document has ended.
|
||
int | visitGlossaryDocumentStart(GlossaryDocument glossary) | |
Called when enumeration of a glossary document has started.
|
||
int | visitGroupShapeEnd(GroupShape groupShape) | |
Called when enumeration of a group shape has ended.
|
||
int | visitGroupShapeStart(GroupShape groupShape) | |
Called when enumeration of a group shape has started.
|
||
int | visitHeaderFooterEnd(HeaderFooter headerFooter) | |
Called when enumeration of a header or footer in a section has ended.
|
||
int | visitHeaderFooterStart(HeaderFooter headerFooter) | |
Called when enumeration of a header or footer in a section has started.
|
||
int | visitOfficeMathEnd(OfficeMath officeMath) | |
Called when enumeration of a Office Math object has ended.
|
||
int | visitOfficeMathStart(OfficeMath officeMath) | |
Called when enumeration of a Office Math object has started.
|
||
int | visitParagraphEnd(Paragraph paragraph) | |
Called when enumeration of a paragraph has ended.
|
||
int | visitParagraphStart(Paragraph paragraph) | |
Called when enumeration of a paragraph has started.
|
||
int | visitRowEnd(Row row) | |
Called when enumeration of a table row has ended.
|
||
int | visitRowStart(Row row) | |
Called when enumeration of a table row has started.
|
||
int | visitRun(Run run) | |
Called when a run of text in the is encountered.
|
||
int | visitSectionEnd(Section section) | |
Called when enumeration of a section has ended.
|
||
int | visitSectionStart(Section section) | |
Called when enumeration of a section has started.
|
||
int | visitShapeEnd(Shape shape) | |
Called when enumeration of a shape has ended.
|
||
int | visitShapeStart(Shape shape) | |
Called when enumeration of a shape has started.
|
||
int | visitSmartTagEnd(SmartTag smartTag) | |
Called when enumeration of a smart tag has ended.
|
||
int | visitSmartTagStart(SmartTag smartTag) | |
Called when enumeration of a smart tag has started.
|
||
int | visitSpecialChar(SpecialChar specialChar) | |
Called when a |
||
int | visitStructuredDocumentTagEnd(StructuredDocumentTag sdt) | |
Called when enumeration of a structured document tag has ended.
|
||
int | visitStructuredDocumentTagRangeEnd(StructuredDocumentTagRangeEnd sdtRangeEnd) | |
int | visitStructuredDocumentTagRangeStart(StructuredDocumentTagRangeStart sdtRangeStart) | |
int | visitStructuredDocumentTagStart(StructuredDocumentTag sdt) | |
Called when enumeration of a structured document tag has started.
|
||
int | visitSubDocument(SubDocument subDocument) | |
Called when a subDocument is encountered.
|
||
int | visitTableEnd(Table table) | |
Called when enumeration of a table has ended.
|
||
int | visitTableStart(Table table) | |
Called when enumeration of a table has started.
|
public int visitAbsolutePositionTab(AbsolutePositionTab tab) throws java.lang.Exception
tab
- The object that is being visited.Example:
Shows how to process absolute position tab characters with a document visitor.public void documentToTxt() throws Exception { Document doc = new Document(getMyDir() + "Absolute position tab.docx"); // Extract the text contents of our document by accepting this custom document visitor. DocTextExtractor myDocTextExtractor = new DocTextExtractor(); doc.getFirstSection().getBody().accept(myDocTextExtractor); // The absolute position tab, which has no equivalent in string form, has been explicitly converted to a tab character. Assert.assertEquals("Before AbsolutePositionTab\tAfter AbsolutePositionTab", myDocTextExtractor.getText()); // An AbsolutePositionTab can accept a DocumentVisitor by itself too. AbsolutePositionTab absPositionTab = (AbsolutePositionTab)doc.getFirstSection().getBody().getFirstParagraph().getChild(NodeType.SPECIAL_CHAR, 0, true); myDocTextExtractor = new DocTextExtractor(); absPositionTab.accept(myDocTextExtractor); Assert.assertEquals("\t", myDocTextExtractor.getText()); } /// <summary> /// Collects the text contents of all runs in the visited document, and represents all absolute tab characters as ordinary tabs. /// </summary> public static class DocTextExtractor extends DocumentVisitor { public DocTextExtractor() { mBuilder = new StringBuilder(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { appendText(run.getText()); return VisitorAction.CONTINUE; } /// <summary> /// Called when an AbsolutePositionTab node is encountered in the document. /// </summary> public int visitAbsolutePositionTab(final AbsolutePositionTab tab) { mBuilder.append("\t"); return VisitorAction.CONTINUE; } /// <summary> /// Adds text to the current output. Honors the enabled/disabled output flag. /// </summary> public void appendText(final String text) { mBuilder.append(text); } /// <summary> /// Plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } private StringBuilder mBuilder; }
public int visitBodyEnd(Body body) throws java.lang.Exception
body
- The object that is being visited.Example:
Shows how to use a document visitor to print a document's node structure.public void docStructureToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); DocStructurePrinter visitor = new DocStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string. /// </summary> public static class DocStructurePrinter extends DocumentVisitor { public DocStructurePrinter() { mAcceptingNodeChildTree = new StringBuilder(); } public String getText() { return mAcceptingNodeChildTree.toString(); } /// <summary> /// Called when a Document node is encountered. /// </summary> public int visitDocumentStart(Document doc) { int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount(); indentAndAppendLine("[Document start] Child nodes: " + childNodeCount); mDocTraversalDepth++; // Allow the visitor to continue visiting other nodes. return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Document node have been visited. /// </summary> public int visitDocumentEnd(Document doc) { mDocTraversalDepth--; indentAndAppendLine("[Document end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Section node is encountered in the document. /// </summary> public int visitSectionStart(final Section section) { // Get the index of our section within the document NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false); int sectionIndex = docSections.indexOf(section); indentAndAppendLine("[Section start] Section index: " + sectionIndex); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Section node have been visited. /// </summary> public int visitSectionEnd(final Section section) { mDocTraversalDepth--; indentAndAppendLine("[Section end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Body node is encountered in the document. /// </summary> public int visitBodyStart(final Body body) { int paragraphCount = body.getParagraphs().getCount(); indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Body node have been visited. /// </summary> public int visitBodyEnd(final Body body) { mDocTraversalDepth--; indentAndAppendLine("[Body end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Paragraph node is encountered in the document. /// </summary> public int visitParagraphStart(final Paragraph paragraph) { indentAndAppendLine("[Paragraph start]"); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Paragraph node have been visited. /// </summary> public int visitParagraphEnd(final Paragraph paragraph) { mDocTraversalDepth--; indentAndAppendLine("[Paragraph end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a SubDocument node is encountered in the document. /// </summary> public int visitSubDocument(final SubDocument subDocument) { indentAndAppendLine("[SubDocument]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mAcceptingNodeChildTree.append("| "); } mAcceptingNodeChildTree.append(text + "\r\n"); } private int mDocTraversalDepth; private StringBuilder mAcceptingNodeChildTree; }
public int visitBodyStart(Body body) throws java.lang.Exception
body
- The object that is being visited.Example:
Shows how to use a document visitor to print a document's node structure.public void docStructureToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); DocStructurePrinter visitor = new DocStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string. /// </summary> public static class DocStructurePrinter extends DocumentVisitor { public DocStructurePrinter() { mAcceptingNodeChildTree = new StringBuilder(); } public String getText() { return mAcceptingNodeChildTree.toString(); } /// <summary> /// Called when a Document node is encountered. /// </summary> public int visitDocumentStart(Document doc) { int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount(); indentAndAppendLine("[Document start] Child nodes: " + childNodeCount); mDocTraversalDepth++; // Allow the visitor to continue visiting other nodes. return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Document node have been visited. /// </summary> public int visitDocumentEnd(Document doc) { mDocTraversalDepth--; indentAndAppendLine("[Document end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Section node is encountered in the document. /// </summary> public int visitSectionStart(final Section section) { // Get the index of our section within the document NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false); int sectionIndex = docSections.indexOf(section); indentAndAppendLine("[Section start] Section index: " + sectionIndex); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Section node have been visited. /// </summary> public int visitSectionEnd(final Section section) { mDocTraversalDepth--; indentAndAppendLine("[Section end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Body node is encountered in the document. /// </summary> public int visitBodyStart(final Body body) { int paragraphCount = body.getParagraphs().getCount(); indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Body node have been visited. /// </summary> public int visitBodyEnd(final Body body) { mDocTraversalDepth--; indentAndAppendLine("[Body end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Paragraph node is encountered in the document. /// </summary> public int visitParagraphStart(final Paragraph paragraph) { indentAndAppendLine("[Paragraph start]"); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Paragraph node have been visited. /// </summary> public int visitParagraphEnd(final Paragraph paragraph) { mDocTraversalDepth--; indentAndAppendLine("[Paragraph end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a SubDocument node is encountered in the document. /// </summary> public int visitSubDocument(final SubDocument subDocument) { indentAndAppendLine("[SubDocument]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mAcceptingNodeChildTree.append("| "); } mAcceptingNodeChildTree.append(text + "\r\n"); } private int mDocTraversalDepth; private StringBuilder mAcceptingNodeChildTree; }
public int visitBookmarkEnd(BookmarkEnd bookmarkEnd) throws java.lang.Exception
bookmarkEnd
- The object that is being visited.Example:
Shows how to add bookmarks and update their contents.public void createUpdateAndPrintBookmarks() throws Exception { // Create a document with three bookmarks, then use a custom document visitor implementation to print their contents. Document doc = createDocumentWithBookmarks(3); BookmarkCollection bookmarks = doc.getRange().getBookmarks(); printAllBookmarkInfo(bookmarks); // Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated. bookmarks.get(0).setName("{bookmarks[0].Name}_NewName"); bookmarks.get("MyBookmark_2").setText("Updated text contents of {bookmarks[1].Name}"); // Print all bookmarks again to see updated values. printAllBookmarkInfo(bookmarks); } /// <summary> /// Create a document with a given number of bookmarks. /// </summary> private static Document createDocumentWithBookmarks(int numberOfBookmarks) throws Exception { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); for (int i = 1; i <= numberOfBookmarks; i++) { String bookmarkName = "MyBookmark_" + i; builder.write("Text before bookmark."); builder.startBookmark(bookmarkName); builder.write(MessageFormat.format("Text inside {0}.", bookmarkName)); builder.endBookmark(bookmarkName); builder.writeln("Text after bookmark."); } return doc; } /// <summary> /// Use an iterator and a visitor to print info of every bookmark in the collection. /// </summary> private static void printAllBookmarkInfo(BookmarkCollection bookmarks) throws Exception { BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter(); // Get each bookmark in the collection to accept a visitor that will print its contents. Iterator<Bookmark> enumerator = bookmarks.iterator(); while (enumerator.hasNext()) { Bookmark currentBookmark = enumerator.next(); if (currentBookmark != null) { currentBookmark.getBookmarkStart().accept(bookmarkVisitor); currentBookmark.getBookmarkEnd().accept(bookmarkVisitor); System.out.println(currentBookmark.getBookmarkStart().getText()); } } } /// <summary> /// Prints contents of every visited bookmark to the console. /// </summary> public static class BookmarkInfoPrinter extends DocumentVisitor { public int visitBookmarkStart(BookmarkStart bookmarkStart) throws Exception { System.out.println(MessageFormat.format("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.getName(), bookmarkStart.getBookmark().getText())); return VisitorAction.CONTINUE; } public int visitBookmarkEnd(BookmarkEnd bookmarkEnd) { System.out.println(MessageFormat.format("BookmarkEnd name: \"{0}\"", bookmarkEnd.getName())); return VisitorAction.CONTINUE; } }
public int visitBookmarkStart(BookmarkStart bookmarkStart) throws java.lang.Exception
bookmarkStart
- The object that is being visited.Example:
Shows how to add bookmarks and update their contents.public void createUpdateAndPrintBookmarks() throws Exception { // Create a document with three bookmarks, then use a custom document visitor implementation to print their contents. Document doc = createDocumentWithBookmarks(3); BookmarkCollection bookmarks = doc.getRange().getBookmarks(); printAllBookmarkInfo(bookmarks); // Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated. bookmarks.get(0).setName("{bookmarks[0].Name}_NewName"); bookmarks.get("MyBookmark_2").setText("Updated text contents of {bookmarks[1].Name}"); // Print all bookmarks again to see updated values. printAllBookmarkInfo(bookmarks); } /// <summary> /// Create a document with a given number of bookmarks. /// </summary> private static Document createDocumentWithBookmarks(int numberOfBookmarks) throws Exception { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); for (int i = 1; i <= numberOfBookmarks; i++) { String bookmarkName = "MyBookmark_" + i; builder.write("Text before bookmark."); builder.startBookmark(bookmarkName); builder.write(MessageFormat.format("Text inside {0}.", bookmarkName)); builder.endBookmark(bookmarkName); builder.writeln("Text after bookmark."); } return doc; } /// <summary> /// Use an iterator and a visitor to print info of every bookmark in the collection. /// </summary> private static void printAllBookmarkInfo(BookmarkCollection bookmarks) throws Exception { BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter(); // Get each bookmark in the collection to accept a visitor that will print its contents. Iterator<Bookmark> enumerator = bookmarks.iterator(); while (enumerator.hasNext()) { Bookmark currentBookmark = enumerator.next(); if (currentBookmark != null) { currentBookmark.getBookmarkStart().accept(bookmarkVisitor); currentBookmark.getBookmarkEnd().accept(bookmarkVisitor); System.out.println(currentBookmark.getBookmarkStart().getText()); } } } /// <summary> /// Prints contents of every visited bookmark to the console. /// </summary> public static class BookmarkInfoPrinter extends DocumentVisitor { public int visitBookmarkStart(BookmarkStart bookmarkStart) throws Exception { System.out.println(MessageFormat.format("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.getName(), bookmarkStart.getBookmark().getText())); return VisitorAction.CONTINUE; } public int visitBookmarkEnd(BookmarkEnd bookmarkEnd) { System.out.println(MessageFormat.format("BookmarkEnd name: \"{0}\"", bookmarkEnd.getName())); return VisitorAction.CONTINUE; } }
public int visitBuildingBlockEnd(BuildingBlock block) throws java.lang.Exception
Note: A building block node and its children are not visited when you execute a
Visitor over a
block
- The object that is being visited.Example:
Shows ways of accessing building blocks in a glossary document.public void glossaryDocument() throws Exception { Document doc = new Document(); GlossaryDocument glossaryDoc = new GlossaryDocument(); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 1")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 2")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 3")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 4")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 5")); Assert.assertEquals(glossaryDoc.getBuildingBlocks().getCount(), 5); doc.setGlossaryDocument(glossaryDoc); // There are various ways of accessing building blocks. // 1 - Get the first/last building blocks in the collection: Assert.assertEquals("Block 1", glossaryDoc.getFirstBuildingBlock().getName()); Assert.assertEquals("Block 5", glossaryDoc.getLastBuildingBlock().getName()); // 2 - Get a building block by index: Assert.assertEquals("Block 2", glossaryDoc.getBuildingBlocks().get(1).getName()); Assert.assertEquals("Block 3", glossaryDoc.getBuildingBlocks().toArray()[2].getName()); // 3 - Get the first building block that matches a gallery, name and category: Assert.assertEquals("Block 4", glossaryDoc.getBuildingBlock(BuildingBlockGallery.ALL, "(Empty Category)", "Block 4").getName()); // We will do that using a custom visitor, // which will give every BuildingBlock in the GlossaryDocument a unique GUID GlossaryDocVisitor visitor = new GlossaryDocVisitor(); glossaryDoc.accept(visitor); System.out.println(visitor.getText()); // When we open this document using Microsoft Word, // we can find the building blocks via Insert -> Quick Parts -> Building Blocks Organizer. doc.save(getArtifactsDir() + "BuildingBlocks.GlossaryDocument.dotx"); } public static BuildingBlock createNewBuildingBlock(final GlossaryDocument glossaryDoc, final String buildingBlockName) { BuildingBlock buildingBlock = new BuildingBlock(glossaryDoc); buildingBlock.setName(buildingBlockName); return buildingBlock; } /// <summary> /// Gives each building block in a visited glossary document a unique GUID, and stores the GUID-building block pairs in a dictionary. /// </summary> public static class GlossaryDocVisitor extends DocumentVisitor { public GlossaryDocVisitor() { mBlocksByGuid = new HashMap<>(); mBuilder = new StringBuilder(); } public String getText() { return mBuilder.toString(); } public HashMap<UUID, BuildingBlock> getDictionary() { return mBlocksByGuid; } public int visitGlossaryDocumentStart(final GlossaryDocument glossary) { mBuilder.append("Glossary document found!\n"); return VisitorAction.CONTINUE; } public int visitGlossaryDocumentEnd(final GlossaryDocument glossary) { mBuilder.append("Reached end of glossary!\n"); mBuilder.append("BuildingBlocks found: " + mBlocksByGuid.size() + "\r\n"); return VisitorAction.CONTINUE; } public int visitBuildingBlockStart(final BuildingBlock block) { block.setGuid(UUID.randomUUID()); mBlocksByGuid.put(block.getGuid(), block); return VisitorAction.CONTINUE; } public int visitBuildingBlockEnd(final BuildingBlock block) { mBuilder.append("\tVisited block \"" + block.getName() + "\"" + "\r\n"); mBuilder.append("\t Type: " + block.getType() + "\r\n"); mBuilder.append("\t Gallery: " + block.getGallery() + "\r\n"); mBuilder.append("\t Behavior: " + block.getBehavior() + "\r\n"); mBuilder.append("\t Description: " + block.getDescription() + "\r\n"); return VisitorAction.CONTINUE; } private HashMap<UUID, BuildingBlock> mBlocksByGuid; private StringBuilder mBuilder; }
public int visitBuildingBlockStart(BuildingBlock block) throws java.lang.Exception
Note: A building block node and its children are not visited when you execute a
Visitor over a
block
- The object that is being visited.Example:
Shows ways of accessing building blocks in a glossary document.public void glossaryDocument() throws Exception { Document doc = new Document(); GlossaryDocument glossaryDoc = new GlossaryDocument(); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 1")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 2")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 3")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 4")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 5")); Assert.assertEquals(glossaryDoc.getBuildingBlocks().getCount(), 5); doc.setGlossaryDocument(glossaryDoc); // There are various ways of accessing building blocks. // 1 - Get the first/last building blocks in the collection: Assert.assertEquals("Block 1", glossaryDoc.getFirstBuildingBlock().getName()); Assert.assertEquals("Block 5", glossaryDoc.getLastBuildingBlock().getName()); // 2 - Get a building block by index: Assert.assertEquals("Block 2", glossaryDoc.getBuildingBlocks().get(1).getName()); Assert.assertEquals("Block 3", glossaryDoc.getBuildingBlocks().toArray()[2].getName()); // 3 - Get the first building block that matches a gallery, name and category: Assert.assertEquals("Block 4", glossaryDoc.getBuildingBlock(BuildingBlockGallery.ALL, "(Empty Category)", "Block 4").getName()); // We will do that using a custom visitor, // which will give every BuildingBlock in the GlossaryDocument a unique GUID GlossaryDocVisitor visitor = new GlossaryDocVisitor(); glossaryDoc.accept(visitor); System.out.println(visitor.getText()); // When we open this document using Microsoft Word, // we can find the building blocks via Insert -> Quick Parts -> Building Blocks Organizer. doc.save(getArtifactsDir() + "BuildingBlocks.GlossaryDocument.dotx"); } public static BuildingBlock createNewBuildingBlock(final GlossaryDocument glossaryDoc, final String buildingBlockName) { BuildingBlock buildingBlock = new BuildingBlock(glossaryDoc); buildingBlock.setName(buildingBlockName); return buildingBlock; } /// <summary> /// Gives each building block in a visited glossary document a unique GUID, and stores the GUID-building block pairs in a dictionary. /// </summary> public static class GlossaryDocVisitor extends DocumentVisitor { public GlossaryDocVisitor() { mBlocksByGuid = new HashMap<>(); mBuilder = new StringBuilder(); } public String getText() { return mBuilder.toString(); } public HashMap<UUID, BuildingBlock> getDictionary() { return mBlocksByGuid; } public int visitGlossaryDocumentStart(final GlossaryDocument glossary) { mBuilder.append("Glossary document found!\n"); return VisitorAction.CONTINUE; } public int visitGlossaryDocumentEnd(final GlossaryDocument glossary) { mBuilder.append("Reached end of glossary!\n"); mBuilder.append("BuildingBlocks found: " + mBlocksByGuid.size() + "\r\n"); return VisitorAction.CONTINUE; } public int visitBuildingBlockStart(final BuildingBlock block) { block.setGuid(UUID.randomUUID()); mBlocksByGuid.put(block.getGuid(), block); return VisitorAction.CONTINUE; } public int visitBuildingBlockEnd(final BuildingBlock block) { mBuilder.append("\tVisited block \"" + block.getName() + "\"" + "\r\n"); mBuilder.append("\t Type: " + block.getType() + "\r\n"); mBuilder.append("\t Gallery: " + block.getGallery() + "\r\n"); mBuilder.append("\t Behavior: " + block.getBehavior() + "\r\n"); mBuilder.append("\t Description: " + block.getDescription() + "\r\n"); return VisitorAction.CONTINUE; } private HashMap<UUID, BuildingBlock> mBlocksByGuid; private StringBuilder mBuilder; }
public int visitCellEnd(Cell cell) throws java.lang.Exception
cell
- The object that is being visited.Example:
Shows how to print the node structure of every table in a document.public void tableToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); TableStructurePrinter visitor = new TableStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Table nodes and their children. /// </summary> public static class TableStructurePrinter extends DocumentVisitor { public TableStructurePrinter() { mVisitedTables = new StringBuilder(); mVisitorIsInsideTable = false; } public String getText() { return mVisitedTables.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// Runs that are not within tables are not recorded. /// </summary> public /*override*/ /*VisitorAction*/int visitRun(Run run) { if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Table is encountered in the document. /// </summary> public int visitTableStart(final Table table) { int rows = 0; int columns = 0; if (table.getRows().getCount() > 0) { rows = table.getRows().getCount(); columns = table.getFirstRow().getCount(); } indentAndAppendLine("[Table start] Size: " + rows + "x" + columns); mDocTraversalDepth++; mVisitorIsInsideTable = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Table node have been visited. /// </summary> public int visitTableEnd(final Table table) { mDocTraversalDepth--; indentAndAppendLine("[Table end]"); mVisitorIsInsideTable = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Row node is encountered in the document. /// </summary> public int visitRowStart(final Row row) { String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", ""); int rowWidth = row.indexOf(row.getLastCell()) + 1; int rowIndex = row.getParentTable().indexOf(row); String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : ""; if (!"".equals(rowStatusInTable)) { rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable); } indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Row node have been visited. /// </summary> public int visitRowEnd(final Row row) { mDocTraversalDepth--; indentAndAppendLine("[Row end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Cell node is encountered in the document. /// </summary> public int visitCellStart(final Cell cell) { Row row = cell.getParentRow(); Table table = row.getParentTable(); String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : ""; if (!"".equals(cellStatusInRow)) { cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow); } indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Cell node have been visited. /// </summary> public int visitCellEnd(final Cell cell) { mDocTraversalDepth--; indentAndAppendLine("[Cell end]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into the current table's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mVisitedTables.append("| "); } mVisitedTables.append(text + "\r\n"); } private boolean mVisitorIsInsideTable; private int mDocTraversalDepth; private /*final*/ StringBuilder mVisitedTables; }
public int visitCellStart(Cell cell) throws java.lang.Exception
cell
- The object that is being visited.Example:
Shows how to print the node structure of every table in a document.public void tableToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); TableStructurePrinter visitor = new TableStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Table nodes and their children. /// </summary> public static class TableStructurePrinter extends DocumentVisitor { public TableStructurePrinter() { mVisitedTables = new StringBuilder(); mVisitorIsInsideTable = false; } public String getText() { return mVisitedTables.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// Runs that are not within tables are not recorded. /// </summary> public /*override*/ /*VisitorAction*/int visitRun(Run run) { if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Table is encountered in the document. /// </summary> public int visitTableStart(final Table table) { int rows = 0; int columns = 0; if (table.getRows().getCount() > 0) { rows = table.getRows().getCount(); columns = table.getFirstRow().getCount(); } indentAndAppendLine("[Table start] Size: " + rows + "x" + columns); mDocTraversalDepth++; mVisitorIsInsideTable = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Table node have been visited. /// </summary> public int visitTableEnd(final Table table) { mDocTraversalDepth--; indentAndAppendLine("[Table end]"); mVisitorIsInsideTable = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Row node is encountered in the document. /// </summary> public int visitRowStart(final Row row) { String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", ""); int rowWidth = row.indexOf(row.getLastCell()) + 1; int rowIndex = row.getParentTable().indexOf(row); String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : ""; if (!"".equals(rowStatusInTable)) { rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable); } indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Row node have been visited. /// </summary> public int visitRowEnd(final Row row) { mDocTraversalDepth--; indentAndAppendLine("[Row end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Cell node is encountered in the document. /// </summary> public int visitCellStart(final Cell cell) { Row row = cell.getParentRow(); Table table = row.getParentTable(); String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : ""; if (!"".equals(cellStatusInRow)) { cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow); } indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Cell node have been visited. /// </summary> public int visitCellEnd(final Cell cell) { mDocTraversalDepth--; indentAndAppendLine("[Cell end]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into the current table's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mVisitedTables.append("| "); } mVisitedTables.append(text + "\r\n"); } private boolean mVisitorIsInsideTable; private int mDocTraversalDepth; private /*final*/ StringBuilder mVisitedTables; }
public int visitCommentEnd(Comment comment) throws java.lang.Exception
comment
- The object that is being visited.Example:
Shows how to print the node structure of every comment and comment range in a document.public void commentsToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); CommentStructurePrinter visitor = new CommentStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Comment/CommentRange nodes and their children. /// </summary> public static class CommentStructurePrinter extends DocumentVisitor { public CommentStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideComment = false; } public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// A Run is only recorded if it is a child of a Comment or CommentRange node. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideComment) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a CommentRangeStart node is encountered in the document. /// </summary> public int visitCommentRangeStart(final CommentRangeStart commentRangeStart) { indentAndAppendLine("[Comment range start] ID: " + commentRangeStart.getId()); mDocTraversalDepth++; mVisitorIsInsideComment = true; return VisitorAction.CONTINUE; } /// <summary> /// Called when a CommentRangeEnd node is encountered in the document. /// </summary> public int visitCommentRangeEnd(final CommentRangeEnd commentRangeEnd) { mDocTraversalDepth--; indentAndAppendLine("[Comment range end]"); mVisitorIsInsideComment = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Comment node is encountered in the document. /// </summary> public int visitCommentStart(final Comment comment) { indentAndAppendLine(MessageFormat.format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.getId(), comment.getAuthor(), comment.getDateTime())); mDocTraversalDepth++; mVisitorIsInsideComment = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Comment node have been visited. /// </summary> public int visitCommentEnd(final Comment comment) { mDocTraversalDepth--; indentAndAppendLine("[Comment end]"); mVisitorIsInsideComment = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into a comment/comment range's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideComment; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitCommentRangeEnd(CommentRangeEnd commentRangeEnd) throws java.lang.Exception
commentRangeEnd
- The object that is being visited.Example:
Shows how to print the node structure of every comment and comment range in a document.public void commentsToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); CommentStructurePrinter visitor = new CommentStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Comment/CommentRange nodes and their children. /// </summary> public static class CommentStructurePrinter extends DocumentVisitor { public CommentStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideComment = false; } public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// A Run is only recorded if it is a child of a Comment or CommentRange node. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideComment) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a CommentRangeStart node is encountered in the document. /// </summary> public int visitCommentRangeStart(final CommentRangeStart commentRangeStart) { indentAndAppendLine("[Comment range start] ID: " + commentRangeStart.getId()); mDocTraversalDepth++; mVisitorIsInsideComment = true; return VisitorAction.CONTINUE; } /// <summary> /// Called when a CommentRangeEnd node is encountered in the document. /// </summary> public int visitCommentRangeEnd(final CommentRangeEnd commentRangeEnd) { mDocTraversalDepth--; indentAndAppendLine("[Comment range end]"); mVisitorIsInsideComment = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Comment node is encountered in the document. /// </summary> public int visitCommentStart(final Comment comment) { indentAndAppendLine(MessageFormat.format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.getId(), comment.getAuthor(), comment.getDateTime())); mDocTraversalDepth++; mVisitorIsInsideComment = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Comment node have been visited. /// </summary> public int visitCommentEnd(final Comment comment) { mDocTraversalDepth--; indentAndAppendLine("[Comment end]"); mVisitorIsInsideComment = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into a comment/comment range's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideComment; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitCommentRangeStart(CommentRangeStart commentRangeStart) throws java.lang.Exception
commentRangeStart
- The object that is being visited.Example:
Shows how to print the node structure of every comment and comment range in a document.public void commentsToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); CommentStructurePrinter visitor = new CommentStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Comment/CommentRange nodes and their children. /// </summary> public static class CommentStructurePrinter extends DocumentVisitor { public CommentStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideComment = false; } public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// A Run is only recorded if it is a child of a Comment or CommentRange node. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideComment) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a CommentRangeStart node is encountered in the document. /// </summary> public int visitCommentRangeStart(final CommentRangeStart commentRangeStart) { indentAndAppendLine("[Comment range start] ID: " + commentRangeStart.getId()); mDocTraversalDepth++; mVisitorIsInsideComment = true; return VisitorAction.CONTINUE; } /// <summary> /// Called when a CommentRangeEnd node is encountered in the document. /// </summary> public int visitCommentRangeEnd(final CommentRangeEnd commentRangeEnd) { mDocTraversalDepth--; indentAndAppendLine("[Comment range end]"); mVisitorIsInsideComment = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Comment node is encountered in the document. /// </summary> public int visitCommentStart(final Comment comment) { indentAndAppendLine(MessageFormat.format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.getId(), comment.getAuthor(), comment.getDateTime())); mDocTraversalDepth++; mVisitorIsInsideComment = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Comment node have been visited. /// </summary> public int visitCommentEnd(final Comment comment) { mDocTraversalDepth--; indentAndAppendLine("[Comment end]"); mVisitorIsInsideComment = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into a comment/comment range's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideComment; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitCommentStart(Comment comment) throws java.lang.Exception
comment
- The object that is being visited.Example:
Shows how to print the node structure of every comment and comment range in a document.public void commentsToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); CommentStructurePrinter visitor = new CommentStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Comment/CommentRange nodes and their children. /// </summary> public static class CommentStructurePrinter extends DocumentVisitor { public CommentStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideComment = false; } public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// A Run is only recorded if it is a child of a Comment or CommentRange node. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideComment) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a CommentRangeStart node is encountered in the document. /// </summary> public int visitCommentRangeStart(final CommentRangeStart commentRangeStart) { indentAndAppendLine("[Comment range start] ID: " + commentRangeStart.getId()); mDocTraversalDepth++; mVisitorIsInsideComment = true; return VisitorAction.CONTINUE; } /// <summary> /// Called when a CommentRangeEnd node is encountered in the document. /// </summary> public int visitCommentRangeEnd(final CommentRangeEnd commentRangeEnd) { mDocTraversalDepth--; indentAndAppendLine("[Comment range end]"); mVisitorIsInsideComment = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Comment node is encountered in the document. /// </summary> public int visitCommentStart(final Comment comment) { indentAndAppendLine(MessageFormat.format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.getId(), comment.getAuthor(), comment.getDateTime())); mDocTraversalDepth++; mVisitorIsInsideComment = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Comment node have been visited. /// </summary> public int visitCommentEnd(final Comment comment) { mDocTraversalDepth--; indentAndAppendLine("[Comment end]"); mVisitorIsInsideComment = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into a comment/comment range's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideComment; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitDocumentEnd(Document doc) throws java.lang.Exception
doc
- The object that is being visited.Example:
Shows how to use a document visitor to print a document's node structure.public void docStructureToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); DocStructurePrinter visitor = new DocStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string. /// </summary> public static class DocStructurePrinter extends DocumentVisitor { public DocStructurePrinter() { mAcceptingNodeChildTree = new StringBuilder(); } public String getText() { return mAcceptingNodeChildTree.toString(); } /// <summary> /// Called when a Document node is encountered. /// </summary> public int visitDocumentStart(Document doc) { int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount(); indentAndAppendLine("[Document start] Child nodes: " + childNodeCount); mDocTraversalDepth++; // Allow the visitor to continue visiting other nodes. return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Document node have been visited. /// </summary> public int visitDocumentEnd(Document doc) { mDocTraversalDepth--; indentAndAppendLine("[Document end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Section node is encountered in the document. /// </summary> public int visitSectionStart(final Section section) { // Get the index of our section within the document NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false); int sectionIndex = docSections.indexOf(section); indentAndAppendLine("[Section start] Section index: " + sectionIndex); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Section node have been visited. /// </summary> public int visitSectionEnd(final Section section) { mDocTraversalDepth--; indentAndAppendLine("[Section end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Body node is encountered in the document. /// </summary> public int visitBodyStart(final Body body) { int paragraphCount = body.getParagraphs().getCount(); indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Body node have been visited. /// </summary> public int visitBodyEnd(final Body body) { mDocTraversalDepth--; indentAndAppendLine("[Body end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Paragraph node is encountered in the document. /// </summary> public int visitParagraphStart(final Paragraph paragraph) { indentAndAppendLine("[Paragraph start]"); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Paragraph node have been visited. /// </summary> public int visitParagraphEnd(final Paragraph paragraph) { mDocTraversalDepth--; indentAndAppendLine("[Paragraph end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a SubDocument node is encountered in the document. /// </summary> public int visitSubDocument(final SubDocument subDocument) { indentAndAppendLine("[SubDocument]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mAcceptingNodeChildTree.append("| "); } mAcceptingNodeChildTree.append(text + "\r\n"); } private int mDocTraversalDepth; private StringBuilder mAcceptingNodeChildTree; }
public int visitDocumentStart(Document doc) throws java.lang.Exception
doc
- The object that is being visited.Example:
Shows how to use a document visitor to print a document's node structure.public void docStructureToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); DocStructurePrinter visitor = new DocStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string. /// </summary> public static class DocStructurePrinter extends DocumentVisitor { public DocStructurePrinter() { mAcceptingNodeChildTree = new StringBuilder(); } public String getText() { return mAcceptingNodeChildTree.toString(); } /// <summary> /// Called when a Document node is encountered. /// </summary> public int visitDocumentStart(Document doc) { int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount(); indentAndAppendLine("[Document start] Child nodes: " + childNodeCount); mDocTraversalDepth++; // Allow the visitor to continue visiting other nodes. return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Document node have been visited. /// </summary> public int visitDocumentEnd(Document doc) { mDocTraversalDepth--; indentAndAppendLine("[Document end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Section node is encountered in the document. /// </summary> public int visitSectionStart(final Section section) { // Get the index of our section within the document NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false); int sectionIndex = docSections.indexOf(section); indentAndAppendLine("[Section start] Section index: " + sectionIndex); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Section node have been visited. /// </summary> public int visitSectionEnd(final Section section) { mDocTraversalDepth--; indentAndAppendLine("[Section end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Body node is encountered in the document. /// </summary> public int visitBodyStart(final Body body) { int paragraphCount = body.getParagraphs().getCount(); indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Body node have been visited. /// </summary> public int visitBodyEnd(final Body body) { mDocTraversalDepth--; indentAndAppendLine("[Body end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Paragraph node is encountered in the document. /// </summary> public int visitParagraphStart(final Paragraph paragraph) { indentAndAppendLine("[Paragraph start]"); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Paragraph node have been visited. /// </summary> public int visitParagraphEnd(final Paragraph paragraph) { mDocTraversalDepth--; indentAndAppendLine("[Paragraph end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a SubDocument node is encountered in the document. /// </summary> public int visitSubDocument(final SubDocument subDocument) { indentAndAppendLine("[SubDocument]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mAcceptingNodeChildTree.append("| "); } mAcceptingNodeChildTree.append(text + "\r\n"); } private int mDocTraversalDepth; private StringBuilder mAcceptingNodeChildTree; }
public int visitEditableRangeEnd(EditableRangeEnd editableRangeEnd) throws java.lang.Exception
editableRangeEnd
- The object that is being visited.Example:
Shows how to print the node structure of every editable range in a document.public void editableRangeToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); EditableRangeStructurePrinter visitor = new EditableRangeStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered EditableRange nodes and their children. /// </summary> public static class EditableRangeStructurePrinter extends DocumentVisitor { public EditableRangeStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideEditableRange = false; } /// <summary> /// Gets the plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { // We want to print the contents of runs, but only if they are inside shapes, as they would be in the case of text boxes if (mVisitorIsInsideEditableRange) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when an EditableRange node is encountered in the document. /// </summary> public int visitEditableRangeStart(final EditableRangeStart editableRangeStart) { indentAndAppendLine("[EditableRange start] ID: " + editableRangeStart.getId() + " Owner: " + editableRangeStart.getEditableRange().getSingleUser()); mDocTraversalDepth++; mVisitorIsInsideEditableRange = true; return VisitorAction.CONTINUE; } /// <summary> /// Called when the visiting of a EditableRange node is ended. /// </summary> public int visitEditableRangeEnd(final EditableRangeEnd editableRangeEnd) { mDocTraversalDepth--; indentAndAppendLine("[EditableRange end]"); mVisitorIsInsideEditableRange = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideEditableRange; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitEditableRangeStart(EditableRangeStart editableRangeStart) throws java.lang.Exception
editableRangeStart
- The object that is being visited.Example:
Shows how to print the node structure of every editable range in a document.public void editableRangeToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); EditableRangeStructurePrinter visitor = new EditableRangeStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered EditableRange nodes and their children. /// </summary> public static class EditableRangeStructurePrinter extends DocumentVisitor { public EditableRangeStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideEditableRange = false; } /// <summary> /// Gets the plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { // We want to print the contents of runs, but only if they are inside shapes, as they would be in the case of text boxes if (mVisitorIsInsideEditableRange) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when an EditableRange node is encountered in the document. /// </summary> public int visitEditableRangeStart(final EditableRangeStart editableRangeStart) { indentAndAppendLine("[EditableRange start] ID: " + editableRangeStart.getId() + " Owner: " + editableRangeStart.getEditableRange().getSingleUser()); mDocTraversalDepth++; mVisitorIsInsideEditableRange = true; return VisitorAction.CONTINUE; } /// <summary> /// Called when the visiting of a EditableRange node is ended. /// </summary> public int visitEditableRangeEnd(final EditableRangeEnd editableRangeEnd) { mDocTraversalDepth--; indentAndAppendLine("[EditableRange end]"); mVisitorIsInsideEditableRange = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideEditableRange; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitFieldEnd(FieldEnd fieldEnd) throws java.lang.Exception
For more info see
fieldEnd
- The object that is being visited.Example:
Shows how to print the node structure of every field in a document.public void fieldToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); FieldStructurePrinter visitor = new FieldStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Field nodes and their children. /// </summary> public static class FieldStructurePrinter extends DocumentVisitor { public FieldStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideField = false; } public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideField) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a FieldStart node is encountered in the document. /// </summary> public int visitFieldStart(final FieldStart fieldStart) { indentAndAppendLine("[Field start] FieldType: " + fieldStart.getFieldType()); mDocTraversalDepth++; mVisitorIsInsideField = true; return VisitorAction.CONTINUE; } /// <summary> /// Called when a FieldEnd node is encountered in the document. /// </summary> public int visitFieldEnd(final FieldEnd fieldEnd) { mDocTraversalDepth--; indentAndAppendLine("[Field end]"); mVisitorIsInsideField = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a FieldSeparator node is encountered in the document. /// </summary> public int visitFieldSeparator(final FieldSeparator fieldSeparator) { indentAndAppendLine("[FieldSeparator]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into the field's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideField; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitFieldSeparator(FieldSeparator fieldSeparator) throws java.lang.Exception
The field separator separates field code from field value in the document. Note that some fields have only field code and do not have field separator and field value.
For more info see
fieldSeparator
- The object that is being visited.Example:
Shows how to print the node structure of every field in a document.public void fieldToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); FieldStructurePrinter visitor = new FieldStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Field nodes and their children. /// </summary> public static class FieldStructurePrinter extends DocumentVisitor { public FieldStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideField = false; } public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideField) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a FieldStart node is encountered in the document. /// </summary> public int visitFieldStart(final FieldStart fieldStart) { indentAndAppendLine("[Field start] FieldType: " + fieldStart.getFieldType()); mDocTraversalDepth++; mVisitorIsInsideField = true; return VisitorAction.CONTINUE; } /// <summary> /// Called when a FieldEnd node is encountered in the document. /// </summary> public int visitFieldEnd(final FieldEnd fieldEnd) { mDocTraversalDepth--; indentAndAppendLine("[Field end]"); mVisitorIsInsideField = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a FieldSeparator node is encountered in the document. /// </summary> public int visitFieldSeparator(final FieldSeparator fieldSeparator) { indentAndAppendLine("[FieldSeparator]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into the field's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideField; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitFieldStart(FieldStart fieldStart) throws java.lang.Exception
A field in a Word Word document consists of a field code and field value.
For example, a field that displays a page number can be represented as follows:
[FieldStart]PAGE[FieldSeparator]98[FieldEnd]
The field separator separates field code from field value in the document. Note that some fields have only field code and do not have field separator and field value.
Fields can be nested.
fieldStart
- The object that is being visited.Example:
Shows how to print the node structure of every field in a document.public void fieldToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); FieldStructurePrinter visitor = new FieldStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Field nodes and their children. /// </summary> public static class FieldStructurePrinter extends DocumentVisitor { public FieldStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideField = false; } public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideField) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a FieldStart node is encountered in the document. /// </summary> public int visitFieldStart(final FieldStart fieldStart) { indentAndAppendLine("[Field start] FieldType: " + fieldStart.getFieldType()); mDocTraversalDepth++; mVisitorIsInsideField = true; return VisitorAction.CONTINUE; } /// <summary> /// Called when a FieldEnd node is encountered in the document. /// </summary> public int visitFieldEnd(final FieldEnd fieldEnd) { mDocTraversalDepth--; indentAndAppendLine("[Field end]"); mVisitorIsInsideField = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a FieldSeparator node is encountered in the document. /// </summary> public int visitFieldSeparator(final FieldSeparator fieldSeparator) { indentAndAppendLine("[FieldSeparator]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into the field's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideField; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitFootnoteEnd(Footnote footnote) throws java.lang.Exception
footnote
- The object that is being visited.Example:
Shows how to print the node structure of every footnote in a document.public void footnoteToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); FootnoteStructurePrinter visitor = new FootnoteStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Footnote nodes and their children. /// </summary> public static class FootnoteStructurePrinter extends DocumentVisitor { public FootnoteStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideFootnote = false; } /// <summary> /// Gets the plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Footnote node is encountered in the document. /// </summary> public int visitFootnoteStart(final Footnote footnote) { indentAndAppendLine("[Footnote start] Type: " + footnote.getFootnoteType()); mDocTraversalDepth++; mVisitorIsInsideFootnote = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Footnote node have been visited. /// </summary> public int visitFootnoteEnd(final Footnote footnote) { mDocTraversalDepth--; indentAndAppendLine("[Footnote end]"); mVisitorIsInsideFootnote = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideFootnote) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideFootnote; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitFootnoteStart(Footnote footnote) throws java.lang.Exception
footnote
- The object that is being visited.Example:
Shows how to print the node structure of every footnote in a document.public void footnoteToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); FootnoteStructurePrinter visitor = new FootnoteStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Footnote nodes and their children. /// </summary> public static class FootnoteStructurePrinter extends DocumentVisitor { public FootnoteStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideFootnote = false; } /// <summary> /// Gets the plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Footnote node is encountered in the document. /// </summary> public int visitFootnoteStart(final Footnote footnote) { indentAndAppendLine("[Footnote start] Type: " + footnote.getFootnoteType()); mDocTraversalDepth++; mVisitorIsInsideFootnote = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Footnote node have been visited. /// </summary> public int visitFootnoteEnd(final Footnote footnote) { mDocTraversalDepth--; indentAndAppendLine("[Footnote end]"); mVisitorIsInsideFootnote = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideFootnote) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideFootnote; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitFormField(FormField formField) throws java.lang.Exception
formField
- The object that is being visited.public int visitGlossaryDocumentEnd(GlossaryDocument glossary) throws java.lang.Exception
Note: A glossary document node and its children are not visited when you execute a
Visitor over a
glossary
- The object that is being visited.Example:
Shows ways of accessing building blocks in a glossary document.public void glossaryDocument() throws Exception { Document doc = new Document(); GlossaryDocument glossaryDoc = new GlossaryDocument(); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 1")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 2")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 3")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 4")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 5")); Assert.assertEquals(glossaryDoc.getBuildingBlocks().getCount(), 5); doc.setGlossaryDocument(glossaryDoc); // There are various ways of accessing building blocks. // 1 - Get the first/last building blocks in the collection: Assert.assertEquals("Block 1", glossaryDoc.getFirstBuildingBlock().getName()); Assert.assertEquals("Block 5", glossaryDoc.getLastBuildingBlock().getName()); // 2 - Get a building block by index: Assert.assertEquals("Block 2", glossaryDoc.getBuildingBlocks().get(1).getName()); Assert.assertEquals("Block 3", glossaryDoc.getBuildingBlocks().toArray()[2].getName()); // 3 - Get the first building block that matches a gallery, name and category: Assert.assertEquals("Block 4", glossaryDoc.getBuildingBlock(BuildingBlockGallery.ALL, "(Empty Category)", "Block 4").getName()); // We will do that using a custom visitor, // which will give every BuildingBlock in the GlossaryDocument a unique GUID GlossaryDocVisitor visitor = new GlossaryDocVisitor(); glossaryDoc.accept(visitor); System.out.println(visitor.getText()); // When we open this document using Microsoft Word, // we can find the building blocks via Insert -> Quick Parts -> Building Blocks Organizer. doc.save(getArtifactsDir() + "BuildingBlocks.GlossaryDocument.dotx"); } public static BuildingBlock createNewBuildingBlock(final GlossaryDocument glossaryDoc, final String buildingBlockName) { BuildingBlock buildingBlock = new BuildingBlock(glossaryDoc); buildingBlock.setName(buildingBlockName); return buildingBlock; } /// <summary> /// Gives each building block in a visited glossary document a unique GUID, and stores the GUID-building block pairs in a dictionary. /// </summary> public static class GlossaryDocVisitor extends DocumentVisitor { public GlossaryDocVisitor() { mBlocksByGuid = new HashMap<>(); mBuilder = new StringBuilder(); } public String getText() { return mBuilder.toString(); } public HashMap<UUID, BuildingBlock> getDictionary() { return mBlocksByGuid; } public int visitGlossaryDocumentStart(final GlossaryDocument glossary) { mBuilder.append("Glossary document found!\n"); return VisitorAction.CONTINUE; } public int visitGlossaryDocumentEnd(final GlossaryDocument glossary) { mBuilder.append("Reached end of glossary!\n"); mBuilder.append("BuildingBlocks found: " + mBlocksByGuid.size() + "\r\n"); return VisitorAction.CONTINUE; } public int visitBuildingBlockStart(final BuildingBlock block) { block.setGuid(UUID.randomUUID()); mBlocksByGuid.put(block.getGuid(), block); return VisitorAction.CONTINUE; } public int visitBuildingBlockEnd(final BuildingBlock block) { mBuilder.append("\tVisited block \"" + block.getName() + "\"" + "\r\n"); mBuilder.append("\t Type: " + block.getType() + "\r\n"); mBuilder.append("\t Gallery: " + block.getGallery() + "\r\n"); mBuilder.append("\t Behavior: " + block.getBehavior() + "\r\n"); mBuilder.append("\t Description: " + block.getDescription() + "\r\n"); return VisitorAction.CONTINUE; } private HashMap<UUID, BuildingBlock> mBlocksByGuid; private StringBuilder mBuilder; }
public int visitGlossaryDocumentStart(GlossaryDocument glossary) throws java.lang.Exception
Note: A glossary document node and its children are not visited when you execute a
Visitor over a
glossary
- The object that is being visited.Example:
Shows ways of accessing building blocks in a glossary document.public void glossaryDocument() throws Exception { Document doc = new Document(); GlossaryDocument glossaryDoc = new GlossaryDocument(); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 1")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 2")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 3")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 4")); glossaryDoc.appendChild(createNewBuildingBlock(glossaryDoc, "Block 5")); Assert.assertEquals(glossaryDoc.getBuildingBlocks().getCount(), 5); doc.setGlossaryDocument(glossaryDoc); // There are various ways of accessing building blocks. // 1 - Get the first/last building blocks in the collection: Assert.assertEquals("Block 1", glossaryDoc.getFirstBuildingBlock().getName()); Assert.assertEquals("Block 5", glossaryDoc.getLastBuildingBlock().getName()); // 2 - Get a building block by index: Assert.assertEquals("Block 2", glossaryDoc.getBuildingBlocks().get(1).getName()); Assert.assertEquals("Block 3", glossaryDoc.getBuildingBlocks().toArray()[2].getName()); // 3 - Get the first building block that matches a gallery, name and category: Assert.assertEquals("Block 4", glossaryDoc.getBuildingBlock(BuildingBlockGallery.ALL, "(Empty Category)", "Block 4").getName()); // We will do that using a custom visitor, // which will give every BuildingBlock in the GlossaryDocument a unique GUID GlossaryDocVisitor visitor = new GlossaryDocVisitor(); glossaryDoc.accept(visitor); System.out.println(visitor.getText()); // When we open this document using Microsoft Word, // we can find the building blocks via Insert -> Quick Parts -> Building Blocks Organizer. doc.save(getArtifactsDir() + "BuildingBlocks.GlossaryDocument.dotx"); } public static BuildingBlock createNewBuildingBlock(final GlossaryDocument glossaryDoc, final String buildingBlockName) { BuildingBlock buildingBlock = new BuildingBlock(glossaryDoc); buildingBlock.setName(buildingBlockName); return buildingBlock; } /// <summary> /// Gives each building block in a visited glossary document a unique GUID, and stores the GUID-building block pairs in a dictionary. /// </summary> public static class GlossaryDocVisitor extends DocumentVisitor { public GlossaryDocVisitor() { mBlocksByGuid = new HashMap<>(); mBuilder = new StringBuilder(); } public String getText() { return mBuilder.toString(); } public HashMap<UUID, BuildingBlock> getDictionary() { return mBlocksByGuid; } public int visitGlossaryDocumentStart(final GlossaryDocument glossary) { mBuilder.append("Glossary document found!\n"); return VisitorAction.CONTINUE; } public int visitGlossaryDocumentEnd(final GlossaryDocument glossary) { mBuilder.append("Reached end of glossary!\n"); mBuilder.append("BuildingBlocks found: " + mBlocksByGuid.size() + "\r\n"); return VisitorAction.CONTINUE; } public int visitBuildingBlockStart(final BuildingBlock block) { block.setGuid(UUID.randomUUID()); mBlocksByGuid.put(block.getGuid(), block); return VisitorAction.CONTINUE; } public int visitBuildingBlockEnd(final BuildingBlock block) { mBuilder.append("\tVisited block \"" + block.getName() + "\"" + "\r\n"); mBuilder.append("\t Type: " + block.getType() + "\r\n"); mBuilder.append("\t Gallery: " + block.getGallery() + "\r\n"); mBuilder.append("\t Behavior: " + block.getBehavior() + "\r\n"); mBuilder.append("\t Description: " + block.getDescription() + "\r\n"); return VisitorAction.CONTINUE; } private HashMap<UUID, BuildingBlock> mBlocksByGuid; private StringBuilder mBuilder; }
public int visitGroupShapeEnd(GroupShape groupShape) throws java.lang.Exception
groupShape
- The object that is being visited.Example:
Shows how to create a group of shapes, and print its contents using a document visitor.public void groupOfShapes() throws Exception { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // If you need to create "NonPrimitive" shapes, such as SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, // TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, DiagonalCornersRounded // please use DocumentBuilder.InsertShape methods. Shape balloon = new Shape(doc, ShapeType.BALLOON); balloon.setWidth(200.0); balloon.setHeight(200.0); balloon.setStrokeColor(Color.RED); Shape cube = new Shape(doc, ShapeType.CUBE); cube.setWidth(100.0); cube.setHeight(100.0); cube.setStrokeColor(Color.BLUE); GroupShape group = new GroupShape(doc); group.appendChild(balloon); group.appendChild(cube); Assert.assertTrue(group.isGroup()); builder.insertNode(group); ShapeInfoPrinter printer = new ShapeInfoPrinter(); group.accept(printer); System.out.println(printer.getText()); } /// <summary> /// Prints the contents of a visited shape group to the console. /// </summary> public static class ShapeInfoPrinter extends DocumentVisitor { public ShapeInfoPrinter() { mBuilder = new StringBuilder(); } public String getText() { return mBuilder.toString(); } public int visitGroupShapeStart(final GroupShape groupShape) { mBuilder.append("Shape group started:\r\n"); return VisitorAction.CONTINUE; } public int visitGroupShapeEnd(final GroupShape groupShape) { mBuilder.append("End of shape group\r\n"); return VisitorAction.CONTINUE; } public int visitShapeStart(final Shape shape) { mBuilder.append("\tShape - " + shape.getShapeType() + ":\r\n"); mBuilder.append("\t\tWidth: " + shape.getWidth() + "\r\n"); mBuilder.append("\t\tHeight: " + shape.getHeight() + "\r\n"); mBuilder.append("\t\tStroke color: " + shape.getStroke().getColor() + "\r\n"); mBuilder.append("\t\tFill color: " + shape.getFill().getColor() + "\r\n"); return VisitorAction.CONTINUE; } public int visitShapeEnd(final Shape shape) { mBuilder.append("\tEnd of shape\r\n"); return VisitorAction.CONTINUE; } private StringBuilder mBuilder; }
public int visitGroupShapeStart(GroupShape groupShape) throws java.lang.Exception
groupShape
- The object that is being visited.Example:
Shows how to create a group of shapes, and print its contents using a document visitor.public void groupOfShapes() throws Exception { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // If you need to create "NonPrimitive" shapes, such as SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, // TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, DiagonalCornersRounded // please use DocumentBuilder.InsertShape methods. Shape balloon = new Shape(doc, ShapeType.BALLOON); balloon.setWidth(200.0); balloon.setHeight(200.0); balloon.setStrokeColor(Color.RED); Shape cube = new Shape(doc, ShapeType.CUBE); cube.setWidth(100.0); cube.setHeight(100.0); cube.setStrokeColor(Color.BLUE); GroupShape group = new GroupShape(doc); group.appendChild(balloon); group.appendChild(cube); Assert.assertTrue(group.isGroup()); builder.insertNode(group); ShapeInfoPrinter printer = new ShapeInfoPrinter(); group.accept(printer); System.out.println(printer.getText()); } /// <summary> /// Prints the contents of a visited shape group to the console. /// </summary> public static class ShapeInfoPrinter extends DocumentVisitor { public ShapeInfoPrinter() { mBuilder = new StringBuilder(); } public String getText() { return mBuilder.toString(); } public int visitGroupShapeStart(final GroupShape groupShape) { mBuilder.append("Shape group started:\r\n"); return VisitorAction.CONTINUE; } public int visitGroupShapeEnd(final GroupShape groupShape) { mBuilder.append("End of shape group\r\n"); return VisitorAction.CONTINUE; } public int visitShapeStart(final Shape shape) { mBuilder.append("\tShape - " + shape.getShapeType() + ":\r\n"); mBuilder.append("\t\tWidth: " + shape.getWidth() + "\r\n"); mBuilder.append("\t\tHeight: " + shape.getHeight() + "\r\n"); mBuilder.append("\t\tStroke color: " + shape.getStroke().getColor() + "\r\n"); mBuilder.append("\t\tFill color: " + shape.getFill().getColor() + "\r\n"); return VisitorAction.CONTINUE; } public int visitShapeEnd(final Shape shape) { mBuilder.append("\tEnd of shape\r\n"); return VisitorAction.CONTINUE; } private StringBuilder mBuilder; }
public int visitHeaderFooterEnd(HeaderFooter headerFooter) throws java.lang.Exception
headerFooter
- The object that is being visited.Example:
Shows how to print the node structure of every header and footer in a document.public void headerFooterToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); HeaderFooterStructurePrinter visitor = new HeaderFooterStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); // An alternative way of accessing a document's header/footers section-by-section is by accessing the collection. HeaderFooter[] headerFooters = doc.getFirstSection().getHeadersFooters().toArray(); Assert.assertEquals(3, headerFooters.length); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered HeaderFooter nodes and their children. /// </summary> public static class HeaderFooterStructurePrinter extends DocumentVisitor { public HeaderFooterStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideHeaderFooter = false; } public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideHeaderFooter) indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a HeaderFooter node is encountered in the document. /// </summary> public int visitHeaderFooterStart(final HeaderFooter headerFooter) { indentAndAppendLine("[HeaderFooter start] HeaderFooterType: " + headerFooter.getHeaderFooterType()); mDocTraversalDepth++; mVisitorIsInsideHeaderFooter = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a HeaderFooter node have been visited. /// </summary> public int visitHeaderFooterEnd(final HeaderFooter headerFooter) { mDocTraversalDepth--; indentAndAppendLine("[HeaderFooter end]"); mVisitorIsInsideHeaderFooter = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideHeaderFooter; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitHeaderFooterStart(HeaderFooter headerFooter) throws java.lang.Exception
headerFooter
- The object that is being visited.Example:
Shows how to print the node structure of every header and footer in a document.public void headerFooterToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); HeaderFooterStructurePrinter visitor = new HeaderFooterStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); // An alternative way of accessing a document's header/footers section-by-section is by accessing the collection. HeaderFooter[] headerFooters = doc.getFirstSection().getHeadersFooters().toArray(); Assert.assertEquals(3, headerFooters.length); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered HeaderFooter nodes and their children. /// </summary> public static class HeaderFooterStructurePrinter extends DocumentVisitor { public HeaderFooterStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideHeaderFooter = false; } public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideHeaderFooter) indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a HeaderFooter node is encountered in the document. /// </summary> public int visitHeaderFooterStart(final HeaderFooter headerFooter) { indentAndAppendLine("[HeaderFooter start] HeaderFooterType: " + headerFooter.getHeaderFooterType()); mDocTraversalDepth++; mVisitorIsInsideHeaderFooter = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a HeaderFooter node have been visited. /// </summary> public int visitHeaderFooterEnd(final HeaderFooter headerFooter) { mDocTraversalDepth--; indentAndAppendLine("[HeaderFooter end]"); mVisitorIsInsideHeaderFooter = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideHeaderFooter; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitOfficeMathEnd(OfficeMath officeMath) throws java.lang.Exception
officeMath
- The object that is being visited.Example:
Shows how to print the node structure of every office math node in a document.public void officeMathToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); OfficeMathStructurePrinter visitor = new OfficeMathStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered OfficeMath nodes and their children. /// </summary> public static class OfficeMathStructurePrinter extends DocumentVisitor { public OfficeMathStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideOfficeMath = false; } /// <summary> /// Gets the plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideOfficeMath) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when an OfficeMath node is encountered in the document. /// </summary> public int visitOfficeMathStart(final OfficeMath officeMath) { indentAndAppendLine("[OfficeMath start] Math object type: " + officeMath.getMathObjectType()); mDocTraversalDepth++; mVisitorIsInsideOfficeMath = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of an OfficeMath node have been visited. /// </summary> public int visitOfficeMathEnd(final OfficeMath officeMath) { mDocTraversalDepth--; indentAndAppendLine("[OfficeMath end]"); mVisitorIsInsideOfficeMath = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideOfficeMath; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitOfficeMathStart(OfficeMath officeMath) throws java.lang.Exception
officeMath
- The object that is being visited.Example:
Shows how to print the node structure of every office math node in a document.public void officeMathToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); OfficeMathStructurePrinter visitor = new OfficeMathStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered OfficeMath nodes and their children. /// </summary> public static class OfficeMathStructurePrinter extends DocumentVisitor { public OfficeMathStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideOfficeMath = false; } /// <summary> /// Gets the plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideOfficeMath) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when an OfficeMath node is encountered in the document. /// </summary> public int visitOfficeMathStart(final OfficeMath officeMath) { indentAndAppendLine("[OfficeMath start] Math object type: " + officeMath.getMathObjectType()); mDocTraversalDepth++; mVisitorIsInsideOfficeMath = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of an OfficeMath node have been visited. /// </summary> public int visitOfficeMathEnd(final OfficeMath officeMath) { mDocTraversalDepth--; indentAndAppendLine("[OfficeMath end]"); mVisitorIsInsideOfficeMath = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideOfficeMath; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitParagraphEnd(Paragraph paragraph) throws java.lang.Exception
paragraph
- The object that is being visited.Example:
Shows how to use a document visitor to print a document's node structure.public void docStructureToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); DocStructurePrinter visitor = new DocStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string. /// </summary> public static class DocStructurePrinter extends DocumentVisitor { public DocStructurePrinter() { mAcceptingNodeChildTree = new StringBuilder(); } public String getText() { return mAcceptingNodeChildTree.toString(); } /// <summary> /// Called when a Document node is encountered. /// </summary> public int visitDocumentStart(Document doc) { int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount(); indentAndAppendLine("[Document start] Child nodes: " + childNodeCount); mDocTraversalDepth++; // Allow the visitor to continue visiting other nodes. return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Document node have been visited. /// </summary> public int visitDocumentEnd(Document doc) { mDocTraversalDepth--; indentAndAppendLine("[Document end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Section node is encountered in the document. /// </summary> public int visitSectionStart(final Section section) { // Get the index of our section within the document NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false); int sectionIndex = docSections.indexOf(section); indentAndAppendLine("[Section start] Section index: " + sectionIndex); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Section node have been visited. /// </summary> public int visitSectionEnd(final Section section) { mDocTraversalDepth--; indentAndAppendLine("[Section end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Body node is encountered in the document. /// </summary> public int visitBodyStart(final Body body) { int paragraphCount = body.getParagraphs().getCount(); indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Body node have been visited. /// </summary> public int visitBodyEnd(final Body body) { mDocTraversalDepth--; indentAndAppendLine("[Body end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Paragraph node is encountered in the document. /// </summary> public int visitParagraphStart(final Paragraph paragraph) { indentAndAppendLine("[Paragraph start]"); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Paragraph node have been visited. /// </summary> public int visitParagraphEnd(final Paragraph paragraph) { mDocTraversalDepth--; indentAndAppendLine("[Paragraph end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a SubDocument node is encountered in the document. /// </summary> public int visitSubDocument(final SubDocument subDocument) { indentAndAppendLine("[SubDocument]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mAcceptingNodeChildTree.append("| "); } mAcceptingNodeChildTree.append(text + "\r\n"); } private int mDocTraversalDepth; private StringBuilder mAcceptingNodeChildTree; }
public int visitParagraphStart(Paragraph paragraph) throws java.lang.Exception
paragraph
- The object that is being visited.Example:
Shows how to use a document visitor to print a document's node structure.public void docStructureToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); DocStructurePrinter visitor = new DocStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string. /// </summary> public static class DocStructurePrinter extends DocumentVisitor { public DocStructurePrinter() { mAcceptingNodeChildTree = new StringBuilder(); } public String getText() { return mAcceptingNodeChildTree.toString(); } /// <summary> /// Called when a Document node is encountered. /// </summary> public int visitDocumentStart(Document doc) { int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount(); indentAndAppendLine("[Document start] Child nodes: " + childNodeCount); mDocTraversalDepth++; // Allow the visitor to continue visiting other nodes. return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Document node have been visited. /// </summary> public int visitDocumentEnd(Document doc) { mDocTraversalDepth--; indentAndAppendLine("[Document end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Section node is encountered in the document. /// </summary> public int visitSectionStart(final Section section) { // Get the index of our section within the document NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false); int sectionIndex = docSections.indexOf(section); indentAndAppendLine("[Section start] Section index: " + sectionIndex); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Section node have been visited. /// </summary> public int visitSectionEnd(final Section section) { mDocTraversalDepth--; indentAndAppendLine("[Section end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Body node is encountered in the document. /// </summary> public int visitBodyStart(final Body body) { int paragraphCount = body.getParagraphs().getCount(); indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Body node have been visited. /// </summary> public int visitBodyEnd(final Body body) { mDocTraversalDepth--; indentAndAppendLine("[Body end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Paragraph node is encountered in the document. /// </summary> public int visitParagraphStart(final Paragraph paragraph) { indentAndAppendLine("[Paragraph start]"); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Paragraph node have been visited. /// </summary> public int visitParagraphEnd(final Paragraph paragraph) { mDocTraversalDepth--; indentAndAppendLine("[Paragraph end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a SubDocument node is encountered in the document. /// </summary> public int visitSubDocument(final SubDocument subDocument) { indentAndAppendLine("[SubDocument]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mAcceptingNodeChildTree.append("| "); } mAcceptingNodeChildTree.append(text + "\r\n"); } private int mDocTraversalDepth; private StringBuilder mAcceptingNodeChildTree; }
public int visitRowEnd(Row row) throws java.lang.Exception
row
- The object that is being visited.Example:
Shows how to print the node structure of every table in a document.public void tableToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); TableStructurePrinter visitor = new TableStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Table nodes and their children. /// </summary> public static class TableStructurePrinter extends DocumentVisitor { public TableStructurePrinter() { mVisitedTables = new StringBuilder(); mVisitorIsInsideTable = false; } public String getText() { return mVisitedTables.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// Runs that are not within tables are not recorded. /// </summary> public /*override*/ /*VisitorAction*/int visitRun(Run run) { if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Table is encountered in the document. /// </summary> public int visitTableStart(final Table table) { int rows = 0; int columns = 0; if (table.getRows().getCount() > 0) { rows = table.getRows().getCount(); columns = table.getFirstRow().getCount(); } indentAndAppendLine("[Table start] Size: " + rows + "x" + columns); mDocTraversalDepth++; mVisitorIsInsideTable = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Table node have been visited. /// </summary> public int visitTableEnd(final Table table) { mDocTraversalDepth--; indentAndAppendLine("[Table end]"); mVisitorIsInsideTable = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Row node is encountered in the document. /// </summary> public int visitRowStart(final Row row) { String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", ""); int rowWidth = row.indexOf(row.getLastCell()) + 1; int rowIndex = row.getParentTable().indexOf(row); String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : ""; if (!"".equals(rowStatusInTable)) { rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable); } indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Row node have been visited. /// </summary> public int visitRowEnd(final Row row) { mDocTraversalDepth--; indentAndAppendLine("[Row end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Cell node is encountered in the document. /// </summary> public int visitCellStart(final Cell cell) { Row row = cell.getParentRow(); Table table = row.getParentTable(); String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : ""; if (!"".equals(cellStatusInRow)) { cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow); } indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Cell node have been visited. /// </summary> public int visitCellEnd(final Cell cell) { mDocTraversalDepth--; indentAndAppendLine("[Cell end]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into the current table's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mVisitedTables.append("| "); } mVisitedTables.append(text + "\r\n"); } private boolean mVisitorIsInsideTable; private int mDocTraversalDepth; private /*final*/ StringBuilder mVisitedTables; }
public int visitRowStart(Row row) throws java.lang.Exception
row
- The object that is being visited.Example:
Shows how to print the node structure of every table in a document.public void tableToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); TableStructurePrinter visitor = new TableStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Table nodes and their children. /// </summary> public static class TableStructurePrinter extends DocumentVisitor { public TableStructurePrinter() { mVisitedTables = new StringBuilder(); mVisitorIsInsideTable = false; } public String getText() { return mVisitedTables.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// Runs that are not within tables are not recorded. /// </summary> public /*override*/ /*VisitorAction*/int visitRun(Run run) { if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Table is encountered in the document. /// </summary> public int visitTableStart(final Table table) { int rows = 0; int columns = 0; if (table.getRows().getCount() > 0) { rows = table.getRows().getCount(); columns = table.getFirstRow().getCount(); } indentAndAppendLine("[Table start] Size: " + rows + "x" + columns); mDocTraversalDepth++; mVisitorIsInsideTable = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Table node have been visited. /// </summary> public int visitTableEnd(final Table table) { mDocTraversalDepth--; indentAndAppendLine("[Table end]"); mVisitorIsInsideTable = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Row node is encountered in the document. /// </summary> public int visitRowStart(final Row row) { String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", ""); int rowWidth = row.indexOf(row.getLastCell()) + 1; int rowIndex = row.getParentTable().indexOf(row); String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : ""; if (!"".equals(rowStatusInTable)) { rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable); } indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Row node have been visited. /// </summary> public int visitRowEnd(final Row row) { mDocTraversalDepth--; indentAndAppendLine("[Row end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Cell node is encountered in the document. /// </summary> public int visitCellStart(final Cell cell) { Row row = cell.getParentRow(); Table table = row.getParentTable(); String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : ""; if (!"".equals(cellStatusInRow)) { cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow); } indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Cell node have been visited. /// </summary> public int visitCellEnd(final Cell cell) { mDocTraversalDepth--; indentAndAppendLine("[Cell end]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into the current table's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mVisitedTables.append("| "); } mVisitedTables.append(text + "\r\n"); } private boolean mVisitorIsInsideTable; private int mDocTraversalDepth; private /*final*/ StringBuilder mVisitedTables; }
public int visitRun(Run run) throws java.lang.Exception
run
- The object that is being visited.Example:
Shows how to use a document visitor to print a document's node structure.public void docStructureToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); DocStructurePrinter visitor = new DocStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string. /// </summary> public static class DocStructurePrinter extends DocumentVisitor { public DocStructurePrinter() { mAcceptingNodeChildTree = new StringBuilder(); } public String getText() { return mAcceptingNodeChildTree.toString(); } /// <summary> /// Called when a Document node is encountered. /// </summary> public int visitDocumentStart(Document doc) { int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount(); indentAndAppendLine("[Document start] Child nodes: " + childNodeCount); mDocTraversalDepth++; // Allow the visitor to continue visiting other nodes. return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Document node have been visited. /// </summary> public int visitDocumentEnd(Document doc) { mDocTraversalDepth--; indentAndAppendLine("[Document end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Section node is encountered in the document. /// </summary> public int visitSectionStart(final Section section) { // Get the index of our section within the document NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false); int sectionIndex = docSections.indexOf(section); indentAndAppendLine("[Section start] Section index: " + sectionIndex); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Section node have been visited. /// </summary> public int visitSectionEnd(final Section section) { mDocTraversalDepth--; indentAndAppendLine("[Section end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Body node is encountered in the document. /// </summary> public int visitBodyStart(final Body body) { int paragraphCount = body.getParagraphs().getCount(); indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Body node have been visited. /// </summary> public int visitBodyEnd(final Body body) { mDocTraversalDepth--; indentAndAppendLine("[Body end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Paragraph node is encountered in the document. /// </summary> public int visitParagraphStart(final Paragraph paragraph) { indentAndAppendLine("[Paragraph start]"); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Paragraph node have been visited. /// </summary> public int visitParagraphEnd(final Paragraph paragraph) { mDocTraversalDepth--; indentAndAppendLine("[Paragraph end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a SubDocument node is encountered in the document. /// </summary> public int visitSubDocument(final SubDocument subDocument) { indentAndAppendLine("[SubDocument]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mAcceptingNodeChildTree.append("| "); } mAcceptingNodeChildTree.append(text + "\r\n"); } private int mDocTraversalDepth; private StringBuilder mAcceptingNodeChildTree; }
public int visitSectionEnd(Section section) throws java.lang.Exception
section
- The object that is being visited.Example:
Shows how to use a document visitor to print a document's node structure.public void docStructureToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); DocStructurePrinter visitor = new DocStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string. /// </summary> public static class DocStructurePrinter extends DocumentVisitor { public DocStructurePrinter() { mAcceptingNodeChildTree = new StringBuilder(); } public String getText() { return mAcceptingNodeChildTree.toString(); } /// <summary> /// Called when a Document node is encountered. /// </summary> public int visitDocumentStart(Document doc) { int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount(); indentAndAppendLine("[Document start] Child nodes: " + childNodeCount); mDocTraversalDepth++; // Allow the visitor to continue visiting other nodes. return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Document node have been visited. /// </summary> public int visitDocumentEnd(Document doc) { mDocTraversalDepth--; indentAndAppendLine("[Document end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Section node is encountered in the document. /// </summary> public int visitSectionStart(final Section section) { // Get the index of our section within the document NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false); int sectionIndex = docSections.indexOf(section); indentAndAppendLine("[Section start] Section index: " + sectionIndex); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Section node have been visited. /// </summary> public int visitSectionEnd(final Section section) { mDocTraversalDepth--; indentAndAppendLine("[Section end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Body node is encountered in the document. /// </summary> public int visitBodyStart(final Body body) { int paragraphCount = body.getParagraphs().getCount(); indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Body node have been visited. /// </summary> public int visitBodyEnd(final Body body) { mDocTraversalDepth--; indentAndAppendLine("[Body end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Paragraph node is encountered in the document. /// </summary> public int visitParagraphStart(final Paragraph paragraph) { indentAndAppendLine("[Paragraph start]"); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Paragraph node have been visited. /// </summary> public int visitParagraphEnd(final Paragraph paragraph) { mDocTraversalDepth--; indentAndAppendLine("[Paragraph end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a SubDocument node is encountered in the document. /// </summary> public int visitSubDocument(final SubDocument subDocument) { indentAndAppendLine("[SubDocument]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mAcceptingNodeChildTree.append("| "); } mAcceptingNodeChildTree.append(text + "\r\n"); } private int mDocTraversalDepth; private StringBuilder mAcceptingNodeChildTree; }
public int visitSectionStart(Section section) throws java.lang.Exception
section
- The object that is being visited.Example:
Shows how to use a document visitor to print a document's node structure.public void docStructureToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); DocStructurePrinter visitor = new DocStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string. /// </summary> public static class DocStructurePrinter extends DocumentVisitor { public DocStructurePrinter() { mAcceptingNodeChildTree = new StringBuilder(); } public String getText() { return mAcceptingNodeChildTree.toString(); } /// <summary> /// Called when a Document node is encountered. /// </summary> public int visitDocumentStart(Document doc) { int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount(); indentAndAppendLine("[Document start] Child nodes: " + childNodeCount); mDocTraversalDepth++; // Allow the visitor to continue visiting other nodes. return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Document node have been visited. /// </summary> public int visitDocumentEnd(Document doc) { mDocTraversalDepth--; indentAndAppendLine("[Document end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Section node is encountered in the document. /// </summary> public int visitSectionStart(final Section section) { // Get the index of our section within the document NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false); int sectionIndex = docSections.indexOf(section); indentAndAppendLine("[Section start] Section index: " + sectionIndex); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Section node have been visited. /// </summary> public int visitSectionEnd(final Section section) { mDocTraversalDepth--; indentAndAppendLine("[Section end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Body node is encountered in the document. /// </summary> public int visitBodyStart(final Body body) { int paragraphCount = body.getParagraphs().getCount(); indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Body node have been visited. /// </summary> public int visitBodyEnd(final Body body) { mDocTraversalDepth--; indentAndAppendLine("[Body end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Paragraph node is encountered in the document. /// </summary> public int visitParagraphStart(final Paragraph paragraph) { indentAndAppendLine("[Paragraph start]"); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Paragraph node have been visited. /// </summary> public int visitParagraphEnd(final Paragraph paragraph) { mDocTraversalDepth--; indentAndAppendLine("[Paragraph end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a SubDocument node is encountered in the document. /// </summary> public int visitSubDocument(final SubDocument subDocument) { indentAndAppendLine("[SubDocument]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mAcceptingNodeChildTree.append("| "); } mAcceptingNodeChildTree.append(text + "\r\n"); } private int mDocTraversalDepth; private StringBuilder mAcceptingNodeChildTree; }
public int visitShapeEnd(Shape shape) throws java.lang.Exception
shape
- The object that is being visited.Example:
Shows how to create a group of shapes, and print its contents using a document visitor.public void groupOfShapes() throws Exception { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // If you need to create "NonPrimitive" shapes, such as SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, // TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, DiagonalCornersRounded // please use DocumentBuilder.InsertShape methods. Shape balloon = new Shape(doc, ShapeType.BALLOON); balloon.setWidth(200.0); balloon.setHeight(200.0); balloon.setStrokeColor(Color.RED); Shape cube = new Shape(doc, ShapeType.CUBE); cube.setWidth(100.0); cube.setHeight(100.0); cube.setStrokeColor(Color.BLUE); GroupShape group = new GroupShape(doc); group.appendChild(balloon); group.appendChild(cube); Assert.assertTrue(group.isGroup()); builder.insertNode(group); ShapeInfoPrinter printer = new ShapeInfoPrinter(); group.accept(printer); System.out.println(printer.getText()); } /// <summary> /// Prints the contents of a visited shape group to the console. /// </summary> public static class ShapeInfoPrinter extends DocumentVisitor { public ShapeInfoPrinter() { mBuilder = new StringBuilder(); } public String getText() { return mBuilder.toString(); } public int visitGroupShapeStart(final GroupShape groupShape) { mBuilder.append("Shape group started:\r\n"); return VisitorAction.CONTINUE; } public int visitGroupShapeEnd(final GroupShape groupShape) { mBuilder.append("End of shape group\r\n"); return VisitorAction.CONTINUE; } public int visitShapeStart(final Shape shape) { mBuilder.append("\tShape - " + shape.getShapeType() + ":\r\n"); mBuilder.append("\t\tWidth: " + shape.getWidth() + "\r\n"); mBuilder.append("\t\tHeight: " + shape.getHeight() + "\r\n"); mBuilder.append("\t\tStroke color: " + shape.getStroke().getColor() + "\r\n"); mBuilder.append("\t\tFill color: " + shape.getFill().getColor() + "\r\n"); return VisitorAction.CONTINUE; } public int visitShapeEnd(final Shape shape) { mBuilder.append("\tEnd of shape\r\n"); return VisitorAction.CONTINUE; } private StringBuilder mBuilder; }
public int visitShapeStart(Shape shape) throws java.lang.Exception
shape
- The object that is being visited.Example:
Shows how to create a group of shapes, and print its contents using a document visitor.public void groupOfShapes() throws Exception { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // If you need to create "NonPrimitive" shapes, such as SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, // TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, DiagonalCornersRounded // please use DocumentBuilder.InsertShape methods. Shape balloon = new Shape(doc, ShapeType.BALLOON); balloon.setWidth(200.0); balloon.setHeight(200.0); balloon.setStrokeColor(Color.RED); Shape cube = new Shape(doc, ShapeType.CUBE); cube.setWidth(100.0); cube.setHeight(100.0); cube.setStrokeColor(Color.BLUE); GroupShape group = new GroupShape(doc); group.appendChild(balloon); group.appendChild(cube); Assert.assertTrue(group.isGroup()); builder.insertNode(group); ShapeInfoPrinter printer = new ShapeInfoPrinter(); group.accept(printer); System.out.println(printer.getText()); } /// <summary> /// Prints the contents of a visited shape group to the console. /// </summary> public static class ShapeInfoPrinter extends DocumentVisitor { public ShapeInfoPrinter() { mBuilder = new StringBuilder(); } public String getText() { return mBuilder.toString(); } public int visitGroupShapeStart(final GroupShape groupShape) { mBuilder.append("Shape group started:\r\n"); return VisitorAction.CONTINUE; } public int visitGroupShapeEnd(final GroupShape groupShape) { mBuilder.append("End of shape group\r\n"); return VisitorAction.CONTINUE; } public int visitShapeStart(final Shape shape) { mBuilder.append("\tShape - " + shape.getShapeType() + ":\r\n"); mBuilder.append("\t\tWidth: " + shape.getWidth() + "\r\n"); mBuilder.append("\t\tHeight: " + shape.getHeight() + "\r\n"); mBuilder.append("\t\tStroke color: " + shape.getStroke().getColor() + "\r\n"); mBuilder.append("\t\tFill color: " + shape.getFill().getColor() + "\r\n"); return VisitorAction.CONTINUE; } public int visitShapeEnd(final Shape shape) { mBuilder.append("\tEnd of shape\r\n"); return VisitorAction.CONTINUE; } private StringBuilder mBuilder; }
public int visitSmartTagEnd(SmartTag smartTag) throws java.lang.Exception
smartTag
- The object that is being visited.Example:
Shows how to print the node structure of every smart tag in a document.public void smartTagToText() throws Exception { Document doc = new Document(getMyDir() + "Smart tags.doc"); SmartTagStructurePrinter visitor = new SmartTagStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); testSmartTagToText(visitor); //ExEnd } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered SmartTag nodes and their children. /// </summary> public static class SmartTagStructurePrinter extends DocumentVisitor { public SmartTagStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideSmartTag = false; } /// <summary> /// Gets the plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideSmartTag) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a SmartTag node is encountered in the document. /// </summary> public int visitSmartTagStart(final SmartTag smartTag) { indentAndAppendLine("[SmartTag start] Name: " + smartTag.getElement()); mDocTraversalDepth++; mVisitorIsInsideSmartTag = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a SmartTag node have been visited. /// </summary> public int visitSmartTagEnd(final SmartTag smartTag) { mDocTraversalDepth--; indentAndAppendLine("[SmartTag end]"); mVisitorIsInsideSmartTag = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideSmartTag; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitSmartTagStart(SmartTag smartTag) throws java.lang.Exception
smartTag
- The object that is being visited.Example:
Shows how to print the node structure of every smart tag in a document.public void smartTagToText() throws Exception { Document doc = new Document(getMyDir() + "Smart tags.doc"); SmartTagStructurePrinter visitor = new SmartTagStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); testSmartTagToText(visitor); //ExEnd } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered SmartTag nodes and their children. /// </summary> public static class SmartTagStructurePrinter extends DocumentVisitor { public SmartTagStructurePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideSmartTag = false; } /// <summary> /// Gets the plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideSmartTag) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a SmartTag node is encountered in the document. /// </summary> public int visitSmartTagStart(final SmartTag smartTag) { indentAndAppendLine("[SmartTag start] Name: " + smartTag.getElement()); mDocTraversalDepth++; mVisitorIsInsideSmartTag = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a SmartTag node have been visited. /// </summary> public int visitSmartTagEnd(final SmartTag smartTag) { mDocTraversalDepth--; indentAndAppendLine("[SmartTag end]"); mVisitorIsInsideSmartTag = false; return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideSmartTag; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitSpecialChar(SpecialChar specialChar) throws java.lang.Exception
specialChar
- The object that is being visited.public int visitStructuredDocumentTagEnd(StructuredDocumentTag sdt) throws java.lang.Exception
sdt
- The object that is being visited.Example:
Shows how to print the node structure of every structured document tag in a document.public void structuredDocumentTagToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); StructuredDocumentTagNodePrinter visitor = new StructuredDocumentTagNodePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered StructuredDocumentTag nodes and their children. /// </summary> public static class StructuredDocumentTagNodePrinter extends DocumentVisitor { public StructuredDocumentTagNodePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideStructuredDocumentTag = false; } /// <summary> /// Gets the plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideStructuredDocumentTag) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a StructuredDocumentTag node is encountered in the document. /// </summary> public int visitStructuredDocumentTagStart(final StructuredDocumentTag sdt) { indentAndAppendLine("[StructuredDocumentTag start] Title: " + sdt.getTitle()); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a StructuredDocumentTag node have been visited. /// </summary> public int visitStructuredDocumentTagEnd(final StructuredDocumentTag sdt) { mDocTraversalDepth--; indentAndAppendLine("[StructuredDocumentTag end]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideStructuredDocumentTag; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitStructuredDocumentTagRangeEnd(StructuredDocumentTagRangeEnd sdtRangeEnd) throws java.lang.Exception
public int visitStructuredDocumentTagRangeStart(StructuredDocumentTagRangeStart sdtRangeStart) throws java.lang.Exception
public int visitStructuredDocumentTagStart(StructuredDocumentTag sdt) throws java.lang.Exception
sdt
- The object that is being visited.Example:
Shows how to print the node structure of every structured document tag in a document.public void structuredDocumentTagToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); StructuredDocumentTagNodePrinter visitor = new StructuredDocumentTagNodePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered StructuredDocumentTag nodes and their children. /// </summary> public static class StructuredDocumentTagNodePrinter extends DocumentVisitor { public StructuredDocumentTagNodePrinter() { mBuilder = new StringBuilder(); mVisitorIsInsideStructuredDocumentTag = false; } /// <summary> /// Gets the plain text of the document that was accumulated by the visitor. /// </summary> public String getText() { return mBuilder.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { if (mVisitorIsInsideStructuredDocumentTag) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); } return VisitorAction.CONTINUE; } /// <summary> /// Called when a StructuredDocumentTag node is encountered in the document. /// </summary> public int visitStructuredDocumentTagStart(final StructuredDocumentTag sdt) { indentAndAppendLine("[StructuredDocumentTag start] Title: " + sdt.getTitle()); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a StructuredDocumentTag node have been visited. /// </summary> public int visitStructuredDocumentTagEnd(final StructuredDocumentTag sdt) { mDocTraversalDepth--; indentAndAppendLine("[StructuredDocumentTag end]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mBuilder.append("| "); } mBuilder.append(text + "\r\n"); } private boolean mVisitorIsInsideStructuredDocumentTag; private int mDocTraversalDepth; private StringBuilder mBuilder; }
public int visitSubDocument(SubDocument subDocument) throws java.lang.Exception
subDocument
- The object that is being visited.Example:
Shows how to use a document visitor to print a document's node structure.public void docStructureToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); DocStructurePrinter visitor = new DocStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's tree of child nodes, and creates a map of this tree in the form of a string. /// </summary> public static class DocStructurePrinter extends DocumentVisitor { public DocStructurePrinter() { mAcceptingNodeChildTree = new StringBuilder(); } public String getText() { return mAcceptingNodeChildTree.toString(); } /// <summary> /// Called when a Document node is encountered. /// </summary> public int visitDocumentStart(Document doc) { int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount(); indentAndAppendLine("[Document start] Child nodes: " + childNodeCount); mDocTraversalDepth++; // Allow the visitor to continue visiting other nodes. return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Document node have been visited. /// </summary> public int visitDocumentEnd(Document doc) { mDocTraversalDepth--; indentAndAppendLine("[Document end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Section node is encountered in the document. /// </summary> public int visitSectionStart(final Section section) { // Get the index of our section within the document NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false); int sectionIndex = docSections.indexOf(section); indentAndAppendLine("[Section start] Section index: " + sectionIndex); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Section node have been visited. /// </summary> public int visitSectionEnd(final Section section) { mDocTraversalDepth--; indentAndAppendLine("[Section end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Body node is encountered in the document. /// </summary> public int visitBodyStart(final Body body) { int paragraphCount = body.getParagraphs().getCount(); indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Body node have been visited. /// </summary> public int visitBodyEnd(final Body body) { mDocTraversalDepth--; indentAndAppendLine("[Body end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Paragraph node is encountered in the document. /// </summary> public int visitParagraphStart(final Paragraph paragraph) { indentAndAppendLine("[Paragraph start]"); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Paragraph node have been visited. /// </summary> public int visitParagraphEnd(final Paragraph paragraph) { mDocTraversalDepth--; indentAndAppendLine("[Paragraph end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. /// </summary> public int visitRun(final Run run) { indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a SubDocument node is encountered in the document. /// </summary> public int visitSubDocument(final SubDocument subDocument) { indentAndAppendLine("[SubDocument]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mAcceptingNodeChildTree.append("| "); } mAcceptingNodeChildTree.append(text + "\r\n"); } private int mDocTraversalDepth; private StringBuilder mAcceptingNodeChildTree; }
public int visitTableEnd(Table table) throws java.lang.Exception
table
- The object that is being visited.Example:
Shows how to print the node structure of every table in a document.public void tableToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); TableStructurePrinter visitor = new TableStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Table nodes and their children. /// </summary> public static class TableStructurePrinter extends DocumentVisitor { public TableStructurePrinter() { mVisitedTables = new StringBuilder(); mVisitorIsInsideTable = false; } public String getText() { return mVisitedTables.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// Runs that are not within tables are not recorded. /// </summary> public /*override*/ /*VisitorAction*/int visitRun(Run run) { if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Table is encountered in the document. /// </summary> public int visitTableStart(final Table table) { int rows = 0; int columns = 0; if (table.getRows().getCount() > 0) { rows = table.getRows().getCount(); columns = table.getFirstRow().getCount(); } indentAndAppendLine("[Table start] Size: " + rows + "x" + columns); mDocTraversalDepth++; mVisitorIsInsideTable = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Table node have been visited. /// </summary> public int visitTableEnd(final Table table) { mDocTraversalDepth--; indentAndAppendLine("[Table end]"); mVisitorIsInsideTable = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Row node is encountered in the document. /// </summary> public int visitRowStart(final Row row) { String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", ""); int rowWidth = row.indexOf(row.getLastCell()) + 1; int rowIndex = row.getParentTable().indexOf(row); String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : ""; if (!"".equals(rowStatusInTable)) { rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable); } indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Row node have been visited. /// </summary> public int visitRowEnd(final Row row) { mDocTraversalDepth--; indentAndAppendLine("[Row end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Cell node is encountered in the document. /// </summary> public int visitCellStart(final Cell cell) { Row row = cell.getParentRow(); Table table = row.getParentTable(); String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : ""; if (!"".equals(cellStatusInRow)) { cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow); } indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Cell node have been visited. /// </summary> public int visitCellEnd(final Cell cell) { mDocTraversalDepth--; indentAndAppendLine("[Cell end]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into the current table's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mVisitedTables.append("| "); } mVisitedTables.append(text + "\r\n"); } private boolean mVisitorIsInsideTable; private int mDocTraversalDepth; private /*final*/ StringBuilder mVisitedTables; }
public int visitTableStart(Table table) throws java.lang.Exception
table
- The object that is being visited.Example:
Shows how to print the node structure of every table in a document.public void tableToText() throws Exception { Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx"); TableStructurePrinter visitor = new TableStructurePrinter(); // When we get a composite node to accept a document visitor, the visitor visits the accepting node, // and then traverses all of the node's children in a depth-first manner. // The visitor can read and modify each visited node. doc.accept(visitor); System.out.println(visitor.getText()); } /// <summary> /// Traverses a node's non-binary tree of child nodes. /// Creates a map in the form of a string of all encountered Table nodes and their children. /// </summary> public static class TableStructurePrinter extends DocumentVisitor { public TableStructurePrinter() { mVisitedTables = new StringBuilder(); mVisitorIsInsideTable = false; } public String getText() { return mVisitedTables.toString(); } /// <summary> /// Called when a Run node is encountered in the document. /// Runs that are not within tables are not recorded. /// </summary> public /*override*/ /*VisitorAction*/int visitRun(Run run) { if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\""); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Table is encountered in the document. /// </summary> public int visitTableStart(final Table table) { int rows = 0; int columns = 0; if (table.getRows().getCount() > 0) { rows = table.getRows().getCount(); columns = table.getFirstRow().getCount(); } indentAndAppendLine("[Table start] Size: " + rows + "x" + columns); mDocTraversalDepth++; mVisitorIsInsideTable = true; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Table node have been visited. /// </summary> public int visitTableEnd(final Table table) { mDocTraversalDepth--; indentAndAppendLine("[Table end]"); mVisitorIsInsideTable = false; return VisitorAction.CONTINUE; } /// <summary> /// Called when a Row node is encountered in the document. /// </summary> public int visitRowStart(final Row row) { String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", ""); int rowWidth = row.indexOf(row.getLastCell()) + 1; int rowIndex = row.getParentTable().indexOf(row); String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : ""; if (!"".equals(rowStatusInTable)) { rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable); } indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Row node have been visited. /// </summary> public int visitRowEnd(final Row row) { mDocTraversalDepth--; indentAndAppendLine("[Row end]"); return VisitorAction.CONTINUE; } /// <summary> /// Called when a Cell node is encountered in the document. /// </summary> public int visitCellStart(final Cell cell) { Row row = cell.getParentRow(); Table table = row.getParentTable(); String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : ""; if (!"".equals(cellStatusInRow)) { cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow); } indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow)); mDocTraversalDepth++; return VisitorAction.CONTINUE; } /// <summary> /// Called after all the child nodes of a Cell node have been visited. /// </summary> public int visitCellEnd(final Cell cell) { mDocTraversalDepth--; indentAndAppendLine("[Cell end]"); return VisitorAction.CONTINUE; } /// <summary> /// Append a line to the StringBuilder, and indent it depending on how deep the visitor is /// into the current table's tree of child nodes. /// </summary> /// <param name="text"></param> private void indentAndAppendLine(final String text) { for (int i = 0; i < mDocTraversalDepth; i++) { mVisitedTables.append("| "); } mVisitedTables.append(text + "\r\n"); } private boolean mVisitorIsInsideTable; private int mDocTraversalDepth; private /*final*/ StringBuilder mVisitedTables; }