com.aspose.words
Class BuildingBlockCollection

java.lang.Object
  extended by NodeCollection
      extended by com.aspose.words.BuildingBlockCollection
All Implemented Interfaces:
java.lang.Iterable

public class BuildingBlockCollection 
extends NodeCollection

A collection of BuildingBlock objects in the document.

You do not create instances of this class directly. To access a collection of building blocks use the GlossaryDocument.BuildingBlocks property.

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 final HashMap<UUID, BuildingBlock> mBlocksByGuid;
    private final StringBuilder mBuilder;
}
See Also:
GlossaryDocument, GlossaryDocument.BuildingBlocks, BuildingBlock

Property Getters/Setters Summary
intgetCount()→ inherited from NodeCollection
           Gets the number of nodes in the collection.
BuildingBlockget(int index)
           Retrieves a building block at the given index.
 
Method Summary
voidadd(Node node)→ inherited from NodeCollection
           Adds a node to the end of the collection.
voidclear()→ inherited from NodeCollection
           Removes all nodes from this collection and from the document.
booleancontains(Node node)→ inherited from NodeCollection
           Determines whether a node is in the collection.
intindexOf(Node node)→ inherited from NodeCollection
           Returns the zero-based index of the specified node.
voidinsert(int index, Node node)→ inherited from NodeCollection
           Inserts a node into the collection at the specified index.
java.util.Iterator<Node>iterator()→ inherited from NodeCollection
           Provides a simple "foreach" style iteration over the collection of nodes.
voidremove(Node node)→ inherited from NodeCollection
           Removes the node from the collection and from the document.
voidremoveAt(int index)→ inherited from NodeCollection
           Removes the node at the specified index from the collection and from the document.
BuildingBlock[]toArray()
           Copies all building blocks from the collection to a new array of building blocks.
 

Property Getters/Setters Detail

getCount

→ inherited from NodeCollection
public int getCount()
Gets the number of nodes in the collection.

Example:

Shows how to traverse through a composite node's collection of child nodes.
Document doc = new Document();

// Add two runs and one shape as child nodes to the first paragraph of this document.
Paragraph paragraph = (Paragraph) doc.getChild(NodeType.PARAGRAPH, 0, true);
paragraph.appendChild(new Run(doc, "Hello world! "));

Shape shape = new Shape(doc, ShapeType.RECTANGLE);
shape.setWidth(200.0);
shape.setHeight(200.0);
shape.setWrapType(WrapType.INLINE);
paragraph.appendChild(shape);

paragraph.appendChild(new Run(doc, "Hello again!"));

// Iterate through the paragraph's collection of immediate children,
// and print any runs or shapes that we find within.
NodeCollection children = paragraph.getChildNodes();

Assert.assertEquals(3, paragraph.getChildNodes().getCount());

for (Node child : (Iterable<Node>) children)
    switch (child.getNodeType()) {
        case NodeType.RUN:
            System.out.println("Run contents:");
            System.out.println("\t\"{child.GetText().Trim()}\"");
            break;
        case NodeType.SHAPE:
            Shape childShape = (Shape) child;
            System.out.println("Shape:");
            System.out.println("\t{childShape.ShapeType}, {childShape.Width}x{childShape.Height}");
            break;
    }

Example:

Shows how to find out if a table contains another table or if the table itself is nested inside another table.
public void calculateDepthOfNestedTables() throws Exception {
    Document doc = new Document(getMyDir() + "Nested tables.docx");
    NodeCollection tables = doc.getChildNodes(NodeType.TABLE, true);

    for (int i = 0; i < tables.getCount(); i++) {
        // First lets find if any cells in the table have tables themselves as children
        int count = getChildTableCount((Table) tables.get(i));
        System.out.println(MessageFormat.format("Table #{0} has {1} tables directly within its cells", i, count));

        // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth
        int tableDepth = getNestedDepthOfTable((Table) tables.get(i));

        if (tableDepth > 0)
            System.out.println(MessageFormat.format("Table #{0} is nested inside another table at depth of {1}", i, tableDepth));
        else
            System.out.println(MessageFormat.format("Table #{0} is a non nested table (is not a child of another table)", i));
    }
}

/**
 * Calculates what level a table is nested inside other tables.
 *
 * @returns An integer containing the level the table is nested at.
 * 0 = Table is not nested inside any other table
 * 1 = Table is nested within one parent table
 * 2 = Table is nested within two parent tables etc..
 */
private static int getNestedDepthOfTable(final Table table) {
    int depth = 0;

    int type = table.getNodeType();
    // The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Node parent = table.getAncestor(table.getNodeType());

    while (parent != null) {
        // Every time we find a table a level up we increase the depth counter and then try to find an
        // ancestor of type table from the parent
        depth++;
        parent = parent.getAncestor(Table.class);
    }

    return depth;
}

/**
 * Determines if a table contains any immediate child table within its cells.
 * Does not recursively traverse through those tables to check for further tables.
 *
 * @returns Returns true if at least one child cell contains a table.
 * Returns false if no cells in the table contains a table.
 */
private static int getChildTableCount(final Table table) {
    int tableCount = 0;
    // Iterate through all child rows in the table
    for (Row row : table.getRows()) {
        // Iterate through all child cells in the row
        for (Cell cell : row.getCells()) {
            // Retrieve the collection of child tables of this cell
            TableCollection childTables = cell.getTables();

            // If this cell has a table as a child then return true
            if (childTables.getCount() > 0) tableCount++;
        }
    }

    // No cell contains a table
    return tableCount;
}

get

public BuildingBlock get(int index)
Retrieves a building block at the given index.

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

Parameters:
index - An index into the list of building blocks.

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 final HashMap<UUID, BuildingBlock> mBlocksByGuid;
    private final StringBuilder mBuilder;
}

Method Detail

add

→ inherited from NodeCollection
public void add(Node node)
        throws java.lang.Exception
Adds a node to the end of the collection.

The node is inserted as a child into the node object from which the collection was created.

If the newChild is already in the tree, it is first removed.

If the node being inserted was created from another document, you should use DocumentBase.importNode(com.aspose.words.Node,boolean,int) to import the node to the current document. The imported node can then be inserted into the current document.

Parameters:
node - The node to be added to the end of the collection.

Example:

Shows how to prepare a new section node for editing.
Document doc = new Document();

// A blank document comes with a section, which has a body, which in turn has a paragraph.
// We can add contents to this document by adding elements such as text runs, shapes, or tables to that paragraph.
Assert.assertEquals(NodeType.SECTION, doc.getChild(NodeType.ANY, 0, true).getNodeType());
Assert.assertEquals(NodeType.BODY, doc.getSections().get(0).getChild(NodeType.ANY, 0, true).getNodeType());
Assert.assertEquals(NodeType.PARAGRAPH, doc.getSections().get(0).getBody().getChild(NodeType.ANY, 0, true).getNodeType());

// If we add a new section like this, it will not have a body, or any other child nodes.
doc.getSections().add(new Section(doc));

Assert.assertEquals(0, doc.getSections().get(1).getChildNodes(NodeType.ANY, true).getCount());

// Run the "EnsureMinumim" method to add a body and a paragraph to this section to begin editing it.
doc.getLastSection().ensureMinimum();

Assert.assertEquals(NodeType.BODY, doc.getSections().get(1).getChild(NodeType.ANY, 0, true).getNodeType());
Assert.assertEquals(NodeType.PARAGRAPH, doc.getSections().get(1).getBody().getChild(NodeType.ANY, 0, true).getNodeType());

doc.getSections().get(0).getBody().getFirstParagraph().appendChild(new Run(doc, "Hello world!"));

Assert.assertEquals("Hello world!", doc.getText().trim());

clear

→ inherited from NodeCollection
public void clear()
Removes all nodes from this collection and from the document.

Example:

Shows how to remove all sections from a document.
Document doc = new Document(getMyDir() + "Document.docx");

// This document has one section with a few child nodes containing and displaying all of the document's contents.
Assert.assertEquals(1, doc.getSections().getCount());
Assert.assertEquals(19, doc.getSections().get(0).getChildNodes(NodeType.ANY, true).getCount());
Assert.assertEquals("Hello World!\r\rHello Word!\r\r\rHello World!", doc.getText().trim());

// Clear the collection of sections, which will remove all of their child nodes, and all of the document's content.
doc.getSections().clear();

Assert.assertEquals(0, doc.getChildNodes(NodeType.ANY, true).getCount());
Assert.assertEquals("", doc.getText().trim());

contains

→ inherited from NodeCollection
public boolean contains(Node node)
Determines whether a node is in the collection.

This method performs a linear search; therefore, the average execution time is proportional to Count.

Parameters:
node - The node to locate.
Returns:
True if item is found in the collection; otherwise, false.

Example:

Shows how to work with a NodeCollection.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add text to the document by inserting Runs using a DocumentBuilder.
builder.write("Run 1. ");
builder.write("Run 2. ");

// Every invocation of the "Write()" method creates a new Run,
// which then appears in the parent Paragraph's RunCollection.
RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();

Assert.assertEquals(2, runs.getCount());

// We can also insert a node into the RunCollection manually.
Run newRun = new Run(doc, "Run 3. ");
runs.insert(3, newRun);

Assert.assertTrue(runs.contains(newRun));
Assert.assertEquals("Run 1. Run 2. Run 3.", doc.getText().trim());

// Access individual runs and remove them to remove their text from the document.
Run run = runs.get(1);
runs.remove(run);

Assert.assertEquals("Run 1. Run 3.", doc.getText().trim());
Assert.assertNotNull(run);
Assert.assertFalse(runs.contains(run));

indexOf

→ inherited from NodeCollection
public int indexOf(Node node)
Returns the zero-based index of the specified node.

This method performs a linear search; therefore, the average execution time is proportional to Count.

Parameters:
node - The node to locate.
Returns:
The zero-based index of the node within the collection, if found; otherwise, -1.

Example:

Shows how to get the indexes of nodes in the collections that contain them.
Document doc = new Document(getMyDir() + "Tables.docx");

Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
NodeCollection allTables = doc.getChildNodes(NodeType.TABLE, true);

Assert.assertEquals(0, allTables.indexOf(table));

Row row = table.getRows().get(2);

Assert.assertEquals(2, table.indexOf(row));

Cell cell = row.getLastCell();

Assert.assertEquals(4, row.indexOf(cell));

insert

→ inherited from NodeCollection
public void insert(int index, Node node)
           throws java.lang.Exception
Inserts a node into the collection at the specified index.

The node is inserted as a child into the node object from which the collection was created.

If the index is equal to or greater than Count, the node is added at the end of the collection.

If the index is negative and its absolute value is greater than Count, the node is added at the end of the collection.

If the newChild is already in the tree, it is first removed.

If the node being inserted was created from another document, you should use DocumentBase.importNode(com.aspose.words.Node,boolean,int) to import the node to the current document. The imported node can then be inserted into the current document.

Parameters:
index - The zero-based index of the node. Negative indexes are allowed and indicate access from the back of the list. For example -1 means the last node, -2 means the second before last and so on.
node - The node to insert.

Example:

Shows how to work with a NodeCollection.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add text to the document by inserting Runs using a DocumentBuilder.
builder.write("Run 1. ");
builder.write("Run 2. ");

// Every invocation of the "Write()" method creates a new Run,
// which then appears in the parent Paragraph's RunCollection.
RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();

Assert.assertEquals(2, runs.getCount());

// We can also insert a node into the RunCollection manually.
Run newRun = new Run(doc, "Run 3. ");
runs.insert(3, newRun);

Assert.assertTrue(runs.contains(newRun));
Assert.assertEquals("Run 1. Run 2. Run 3.", doc.getText().trim());

// Access individual runs and remove them to remove their text from the document.
Run run = runs.get(1);
runs.remove(run);

Assert.assertEquals("Run 1. Run 3.", doc.getText().trim());
Assert.assertNotNull(run);
Assert.assertFalse(runs.contains(run));

iterator

→ inherited from NodeCollection
public java.util.Iterator<Nodeiterator()
Provides a simple "foreach" style iteration over the collection of nodes.
Returns:
An Iterator.

remove

→ inherited from NodeCollection
public void remove(Node node)
Removes the node from the collection and from the document.
Parameters:
node - The node to remove.

Example:

Shows how to work with a NodeCollection.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add text to the document by inserting Runs using a DocumentBuilder.
builder.write("Run 1. ");
builder.write("Run 2. ");

// Every invocation of the "Write()" method creates a new Run,
// which then appears in the parent Paragraph's RunCollection.
RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();

Assert.assertEquals(2, runs.getCount());

// We can also insert a node into the RunCollection manually.
Run newRun = new Run(doc, "Run 3. ");
runs.insert(3, newRun);

Assert.assertTrue(runs.contains(newRun));
Assert.assertEquals("Run 1. Run 2. Run 3.", doc.getText().trim());

// Access individual runs and remove them to remove their text from the document.
Run run = runs.get(1);
runs.remove(run);

Assert.assertEquals("Run 1. Run 3.", doc.getText().trim());
Assert.assertNotNull(run);
Assert.assertFalse(runs.contains(run));

removeAt

→ inherited from NodeCollection
public void removeAt(int index)
Removes the node at the specified index from the collection and from the document.
Parameters:
index - The zero-based index of the node. Negative indexes are allowed and indicate access from the back of the list. For example -1 means the last node, -2 means the second before last and so on.

Example:

Shows how to add and remove sections in a document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.write("Section 1");
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
builder.write("Section 2");

Assert.assertEquals("Section 1\fSection 2", doc.getText().trim());

// Delete the first section from the document.
doc.getSections().removeAt(0);

Assert.assertEquals("Section 2", doc.getText().trim());

// Append a copy of what is now the first section to the end of the document.
int lastSectionIdx = doc.getSections().getCount() - 1;
Section newSection = doc.getSections().get(lastSectionIdx).deepClone();
doc.getSections().add(newSection);

Assert.assertEquals("Section 2\fSection 2", doc.getText().trim());

toArray

public BuildingBlock[] toArray()
Copies all building blocks from the collection to a new array of building blocks.
Returns:
An array of building blocks.

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 final HashMap<UUID, BuildingBlock> mBlocksByGuid;
    private final StringBuilder mBuilder;
}

See Also:
          Aspose.Words Documentation - the home page for the Aspose.Words Product Documentation.
          Aspose.Words Support Forum - our preferred method of support.