Aspose::Words::CompositeNode Class Referenceabstract

Detailed Description

Base class for nodes that can contain other nodes.

A document is represented as a tree of nodes, similar to DOM or XmlDocument.

For more info see the Composite design pattern.

The CompositeNode class:

  • Provides access to the child nodes.
  • Implements Composite operations such as insert and remove children.
  • Provides methods for XPath navigation.
Examples

Shows how to enumerate immediate children of a CompositeNode using the enumerator provided by the ChildNodes collection.

auto doc = MakeObject<Document>();
auto paragraph = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 0, true));
paragraph->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
paragraph->AppendChild(MakeObject<Run>(doc, u" Hello again!"));
SharedPtr<NodeCollection> children = paragraph->get_ChildNodes();
// Paragraph may contain children of various types such as runs, shapes and so on
for (auto child : System::IterateOver(children))
{
if (child->get_NodeType() == NodeType::Run)
{
auto run = System::DynamicCast<Run>(child);
System::Console::WriteLine(run->get_Text());
}
}

#include <Aspose.Words.Cpp/Model/Nodes/CompositeNode.h>

+ Inheritance diagram for Aspose::Words::CompositeNode:

Public Member Functions

SharedPtr< NodeAppendChild (SharedPtr< Node > newChild)
 Adds the specified node to the end of the list of child nodes for this node. More...
 
SharedPtr< NodeCollectionget_ChildNodes ()
 Gets all immediate child nodes of this node. More...
 
SharedPtr< CompositeNodeget_Container () override
 
int32_t get_Count ()
 Gets the number of immediate children of this node. More...
 
SharedPtr< Nodeget_FirstChild () const
 Gets the first child of the node. More...
 
bool get_HasChildNodes ()
 Returns true if this node has any child nodes. More...
 
bool get_IsComposite () override
 Returns true as this node can have child nodes. More...
 
SharedPtr< Nodeget_LastChild () const
 Gets the last child of the node. More...
 
SharedPtr< NodeGetChild (NodeType nodeType, int32_t index, bool isDeep)
 Returns an Nth child node that matches the specified type. More...
 
SharedPtr< NodeCollectionGetChildNodes (NodeType nodeType, bool isDeep)
 Returns a live collection of child nodes that match the specified type. More...
 
SharedPtr< NodeGetCurrentNode () override
 
SharedPtr< IEnumerator< SharedPtr< Node > > > GetEnumerator () override
 Provides support for the for each style iteration over the child nodes of this node. More...
 
SharedPtr< NodeGetNextMatchingNode (SharedPtr< Node > curNode) override
 
String GetText () override
 Gets the text of this node and of all its children. More...
 
virtual const TypeInfoGetType () const override
 
int32_t IndexOf (SharedPtr< Node > child)
 Returns the index of the specified child node in the child node array. More...
 
SharedPtr< NodeInsertAfter (SharedPtr< Node > newChild, SharedPtr< Node > refChild)
 Inserts the specified node immediately after the specified reference node. More...
 
SharedPtr< NodeInsertBefore (SharedPtr< Node > newChild, SharedPtr< Node > refChild)
 Inserts the specified node immediately before the specified reference node. More...
 
virtual bool Is (const TypeInfo &target) const override
 
SharedPtr< NodePrependChild (SharedPtr< Node > newChild)
 Adds the specified node to the beginning of the list of child nodes for this node. More...
 
void RemoveAllChildren ()
 Removes all the child nodes of the current node. More...
 
SharedPtr< NodeRemoveChild (SharedPtr< Node > oldChild)
 Removes the specified child node. More...
 
void RemoveSmartTags ()
 Removes all SmartTag descendant nodes of the current node. More...
 
SharedPtr< NodeListSelectNodes (String xpath)
 Selects a list of nodes matching the XPath expression. More...
 
SharedPtr< NodeSelectSingleNode (String xpath)
 Selects the first Node that matches the XPath expression. More...
 
- Public Member Functions inherited from Node
virtual bool Accept (SharedPtr< DocumentVisitor > visitor)=0
 Accepts a visitor. More...
 
SharedPtr< NodeClone (bool isCloneChildren)
 
virtual SharedPtr< DocumentBaseget_Document () const
 Gets the document to which this node belongs. More...
 
SharedPtr< Nodeget_NextSibling ()
 Gets the node immediately following this node. More...
 
virtual NodeType get_NodeType () const =0
 Gets the type of this node. More...
 
SharedPtr< CompositeNodeget_ParentNode ()
 Gets the immediate parent of this node. More...
 
SharedPtr< Nodeget_PreviousSibling ()
 Gets the node immediately preceding this node. More...
 
SharedPtr< Rangeget_Range ()
 Returns a Range object that represents the portion of a document that is contained in this node. More...
 
SharedPtr< CompositeNodeGetAncestor (NodeType ancestorType)
 Gets the first ancestor of the specified NodeType. More...
 
template<typename T >
GetAncestorOf ()
 
SharedPtr< NodeNextPreOrder (SharedPtr< Node > rootNode)
 Gets next node according to the pre-order tree traversal algorithm. More...
 
SharedPtr< NodePreviousPreOrder (SharedPtr< Node > rootNode)
 Gets the previous node according to the pre-order tree traversal algorithm. More...
 
void Remove ()
 Removes itself from the parent. More...
 
String ToString (SaveFormat saveFormat)
 Exports the content of the node into a string in the specified format. More...
 
String ToString (SharedPtr< SaveOptions > saveOptions)
 Exports the content of the node into a string using the specified save options. More...
 
- Public Member Functions inherited from Object
ASPOSECPP_SHARED_API Object ()
 
ASPOSECPP_SHARED_API Object (Object const &x)
 
virtual ASPOSECPP_SHARED_API ~Object ()
 
virtual ASPOSECPP_SHARED_API bool Equals (ptr obj)
 
Detail::SmartPtrCounter * GetCounter ()
 
virtual ASPOSECPP_SHARED_API int GetHashCode () const
 
ASPOSECPP_SHARED_API void Lock ()
 
virtual ASPOSECPP_SHARED_API ptr MemberwiseClone () const
 
Objectoperator= (Object const &x)
 
bool ReferenceEquals (String const &str, std::nullptr_t)
 
bool ReferenceEquals (String const &str1, String const &str2)
 
int RemovedSharedRefs (int count)
 
virtual ASPOSECPP_SHARED_API void SetTemplateWeakPtr (unsigned int argument)
 
int SharedCount () const
 
ObjectSharedRefAdded ()
 
int SharedRefRemovedSafe ()
 
virtual ASPOSECPP_SHARED_API String ToString () const
 
ASPOSECPP_SHARED_API void Unlock ()
 
Detail::SmartPtrCounter * WeakRefAdded ()
 
void WeakRefRemoved ()
 
- Public Member Functions inherited from System::Collections::Generic::IEnumerable< System::SharedPtr< Aspose::Words::Node > >
EnumeratorBasedIterator< T, IEnumerator< T > > begin () noexcept
 
EnumeratorBasedIterator< T, IEnumerator< T > > cbegin () noexcept
 
EnumeratorBasedIterator< T, IEnumerator< T > > cend () noexcept
 
EnumeratorBasedIterator< T, IEnumerator< T > > end () noexcept
 
bool LINQ_All (std::function< bool(T)> predicate)
 
bool LINQ_Any ()
 
bool LINQ_Any (std::function< bool(T)> predicate)
 
SharedPtr< IEnumerable< ResultType > > LINQ_Cast ()
 
SharedPtr< IEnumerable< Result > > LINQ_Cast ()
 
bool LINQ_Contains (T value)
 
int LINQ_Count ()
 
int LINQ_Count (const Func< T, bool > &predicate)
 
LINQ_ElementAt (int index)
 
LINQ_First ()
 
LINQ_First (const Func< T, bool > &predicate)
 
LINQ_FirstOrDefault ()
 
LINQ_FirstOrDefault (std::function< bool(T)> predicate)
 
LINQ_Last ()
 
LINQ_LastOrDefault ()
 
SharedPtr< IEnumerable< ResultType > > LINQ_OfType ()
 
SharedPtr< IEnumerable< Result > > LINQ_OfType ()
 
SharedPtr< IEnumerable< Source > > LINQ_OrderBy (const Func< Source, Key > &keySelector)
 
SharedPtr< IEnumerable< T > > LINQ_OrderBy (const Func< T, Key > &keySelector)
 
SharedPtr< IEnumerable< Result > > LINQ_Select (const Func< Source, Result > &selector)
 
SharedPtr< IEnumerable< ResultType > > LINQ_Select (const Func< T, ResultType > &selector)
 
ArrayPtr< T > LINQ_ToArray ()
 
SharedPtr< List< T > > LINQ_ToList ()
 
SharedPtr< IEnumerable< T > > LINQ_Where (std::function< bool(T)> predicate)
 

Static Public Member Functions

static const TypeInfoType ()
 
- Static Public Member Functions inherited from Node
static String NodeTypeToString (NodeType nodeType)
 A utility method that converts a node type enum value into a user friendly string. More...
 
static const TypeInfoType ()
 
- Static Public Member Functions inherited from Object
bool Equals (double const &objA, double const &objB)
 
bool Equals (float const &objA, float const &objB)
 
static std::enable_if<!IsSmartPtr< T1 >::value &&!IsSmartPtr< T2 >::value, bool >::type Equals (T1 const &objA, T2 const &objB)
 
static std::enable_if< IsSmartPtr< T1 >::value &&IsSmartPtr< T2 >::value, bool >::type Equals (T1 const &objA, T2 const &objB)
 
static bool ReferenceEquals (ptr const &objA, ptr const &objB)
 
static std::enable_if<!IsSmartPtr< T >::value, bool >::type ReferenceEquals (T const &objA, std::nullptr_t)
 
static std::enable_if<!IsSmartPtr< T >::value, bool >::type ReferenceEquals (T const &objA, T const &objB)
 
static const TypeInfoType ()
 

Additional Inherited Members

- Public Types inherited from Object
typedef SmartPtr< Objectptr
 
typedef System::Details::SharedMembersType shared_members_type
 
- Public Types inherited from System::Collections::Generic::IEnumerable< System::SharedPtr< Aspose::Words::Node > >
typedef IEnumerator< T > IEnumeratorType
 
typedef T ValueType
 

Member Function Documentation

◆ AppendChild()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::AppendChild ( System::SharedPtr< Aspose::Words::Node newChild)

Adds the specified node to the end of the list of child nodes for this node.

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 ImportNode() to import the node to the current document. The imported node can then be inserted into the current document.

Parameters
newChildThe node to add.
Returns
The node added.
Examples

Shows how to construct an Aspose Words document node by node.

auto doc = MakeObject<Document>();
// A newly created blank document still comes one section, one body and one paragraph
// Calling this method will remove all those nodes to completely empty the document
doc->RemoveAllChildren();
// This document now has no composite nodes that content can be added to
// If we wish to edit it, we will need to repopulate its node collection,
// which we will start to do with by creating a new Section node
auto section = MakeObject<Section>(doc);
// Append the section to the document
doc->AppendChild(section);
// Lets set some properties for the section
section->get_PageSetup()->set_SectionStart(SectionStart::NewPage);
section->get_PageSetup()->set_PaperSize(PaperSize::Letter);
// The section that we created is empty, lets populate it. The section needs at least the Body node
auto body = MakeObject<Body>(doc);
section->AppendChild(body);
// The body needs to have at least one paragraph
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information
auto para = MakeObject<Paragraph>(doc);
body->AppendChild(para);
// We can set some formatting for the paragraph
para->get_ParagraphFormat()->set_StyleName(u"Heading 1");
para->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
// So far we have one empty paragraph in the document
// The document is valid and can be saved, but lets add some text before saving
// Create a new run of text and add it to our paragraph
auto run = MakeObject<Run>(doc);
run->set_Text(u"Hello World!");
run->get_Font()->set_Color(System::Drawing::Color::get_Red());
para->AppendChild(run);
ASSERT_EQ(String(u"Hello World!") + ControlChar::SectionBreakChar, doc->GetText());
doc->Save(ArtifactsDir + u"Section.CreateFromScratch.docx");

◆ get_ChildNodes()

System::SharedPtr<Aspose::Words::NodeCollection> Aspose::Words::CompositeNode::get_ChildNodes ( )

Gets all immediate child nodes of this node.

Note, ChildNodes is equivalent to calling GetChildNodes(NodeType.Any, false) and creates and returns a new collection every time it is accessed.

If there are no child nodes, this property returns an empty collection.

Examples

Shows how to enumerate immediate children of a CompositeNode using the enumerator provided by the ChildNodes collection.

auto doc = MakeObject<Document>();
auto paragraph = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 0, true));
paragraph->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
paragraph->AppendChild(MakeObject<Run>(doc, u" Hello again!"));
SharedPtr<NodeCollection> children = paragraph->get_ChildNodes();
// Paragraph may contain children of various types such as runs, shapes and so on
for (auto child : System::IterateOver(children))
{
if (child->get_NodeType() == NodeType::Run)
{
auto run = System::DynamicCast<Run>(child);
System::Console::WriteLine(run->get_Text());
}
}

◆ get_Container()

System::SharedPtr<Aspose::Words::CompositeNode> Aspose::Words::CompositeNode::get_Container ( )
override

◆ get_Count()

int32_t Aspose::Words::CompositeNode::get_Count ( )

Gets the number of immediate children of this node.

Examples

Shows how to add, update and delete child nodes from a CompositeNode's child collection.

auto doc = MakeObject<Document>();
// An empty document has one paragraph by default
ASSERT_EQ(1, doc->get_FirstSection()->get_Body()->get_Paragraphs()->get_Count());
// A paragraph is a composite node because it can contain runs, which are another type of node
SharedPtr<Paragraph> paragraph = doc->get_FirstSection()->get_Body()->get_FirstParagraph();
auto paragraphText = MakeObject<Run>(doc, u"Initial text. ");
paragraph->AppendChild(paragraphText);
// We will place these 3 children into the main text of our paragraph
auto run1 = MakeObject<Run>(doc, u"Run 1. ");
auto run2 = MakeObject<Run>(doc, u"Run 2. ");
auto run3 = MakeObject<Run>(doc, u"Run 3. ");
// We initialized them but not in our paragraph yet
ASSERT_EQ(u"Initial text.", paragraph->GetText().Trim());
// Insert run2 before initial paragraph text. This will be at the start of the paragraph
paragraph->InsertBefore(run2, paragraphText);
// Insert run3 after initial paragraph text. This will be at the end of the paragraph
paragraph->InsertAfter(run3, paragraphText);
// Insert run1 before every other child node. run2 was the start of the paragraph, now it will be run1
paragraph->PrependChild(run1);
ASSERT_EQ(u"Run 1. Run 2. Initial text. Run 3.", paragraph->GetText().Trim());
ASSERT_EQ(4, paragraph->GetChildNodes(NodeType::Any, true)->get_Count());
// Access the child node collection and update/delete children
(System::DynamicCast<Run>(paragraph->GetChildNodes(NodeType::Run, true)->idx_get(1)))->set_Text(u"Updated run 2. ");
paragraph->GetChildNodes(NodeType::Run, true)->Remove(paragraphText);
ASSERT_EQ(u"Run 1. Updated run 2. Run 3.", paragraph->GetText().Trim());
ASSERT_EQ(3, paragraph->GetChildNodes(NodeType::Any, true)->get_Count());

◆ get_FirstChild()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::get_FirstChild ( ) const

Gets the first child of the node.

Examples

Shows how to enumerate immediate child nodes of a composite node using NextSibling.

auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
// Loop starting from the first child until we reach null
for (SharedPtr<Node> node = doc->get_FirstSection()->get_Body()->get_FirstChild(); node != nullptr; node = node->get_NextSibling())
{
// Output the types of the nodes that we come across
}

◆ get_HasChildNodes()

bool Aspose::Words::CompositeNode::get_HasChildNodes ( )

Returns true if this node has any child nodes.

Examples

Shows how to combine the rows from two tables into one.

// Load the document
auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
// Get the first and second table in the document
// The rows from the second table will be appended to the end of the first table
auto firstTable = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
auto secondTable = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 1, true));
// Append all rows from the current table to the next
// Due to the design of tables even tables with different cell count and widths can be joined into one table
while (secondTable->get_HasChildNodes())
{
firstTable->get_Rows()->Add(secondTable->get_FirstRow());
}
// Remove the empty table container
secondTable->Remove();
doc->Save(ArtifactsDir + u"Table.CombineTables.docx");

◆ get_IsComposite()

bool Aspose::Words::CompositeNode::get_IsComposite ( )
overridevirtual

Returns true as this node can have child nodes.

Reimplemented from Aspose::Words::Node.

◆ get_LastChild()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::get_LastChild ( ) const

Gets the last child of the node.

Examples

Shows how to use of methods of Node and CompositeNode to remove a section before the last section in the document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a second section by inserting a section break and add text to both sections
builder->Writeln(u"Section 1 text.");
builder->InsertBreak(BreakType::SectionBreakContinuous);
builder->Writeln(u"Section 2 text.");
// Both sections are siblings of each other
auto lastSection = System::DynamicCast<Section>(doc->get_LastChild());
auto firstSection = System::DynamicCast<Section>(lastSection->get_PreviousSibling());
// Remove a section based on its sibling relationship with another section
if (lastSection->get_PreviousSibling() != nullptr)
{
doc->RemoveChild(firstSection);
}
// The section we removed was the first one, leaving the document with only the second
ASSERT_EQ(u"Section 2 text.", doc->GetText().Trim());

◆ GetChild()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::GetChild ( Aspose::Words::NodeType  nodeType,
int32_t  index,
bool  isDeep 
)

Returns an Nth child node that matches the specified type.

If index is out of range, a null is returned.

Parameters
nodeTypeSpecifies the type of the child node.
indexZero based index of the child node to select. Negative indexes are also allowed and indicate access from the end, that is -1 means the last node.
isDeepTrue to select from all child nodes recursively. False to select only among immediate children. See remarks for more info.
Returns
The child node that matches the criteria or null if no matching node is found.
Examples

Shows how to expand the formatting from styles onto the rows and cells of the table as direct formatting.

auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// First print the color of the cell shading. This should be empty as the current shading
// is stored in the table style
double cellShadingBefore = table->get_FirstRow()->get_RowFormat()->get_Height();
System::Console::WriteLine(String(u"Cell shading before style expansion: ") + cellShadingBefore);
// Expand table style formatting to direct formatting
doc->ExpandTableStylesToDirectFormatting();
// Now print the cell shading after expanding table styles. A blue background pattern color
// should have been applied from the table style
double cellShadingAfter = table->get_FirstRow()->get_RowFormat()->get_Height();
System::Console::WriteLine(String(u"Cell shading after style expansion: ") + cellShadingAfter);
doc->Save(ArtifactsDir + u"Document.TableStyleToDirectFormatting.docx");

Shows how to enumerate immediate children of a CompositeNode using the enumerator provided by the ChildNodes collection.

auto doc = MakeObject<Document>();
auto paragraph = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 0, true));
paragraph->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
paragraph->AppendChild(MakeObject<Run>(doc, u" Hello again!"));
SharedPtr<NodeCollection> children = paragraph->get_ChildNodes();
// Paragraph may contain children of various types such as runs, shapes and so on
for (auto child : System::IterateOver(children))
{
if (child->get_NodeType() == NodeType::Run)
{
auto run = System::DynamicCast<Run>(child);
System::Console::WriteLine(run->get_Text());
}
}

◆ GetChildNodes()

System::SharedPtr<Aspose::Words::NodeCollection> Aspose::Words::CompositeNode::GetChildNodes ( Aspose::Words::NodeType  nodeType,
bool  isDeep 
)

Returns a live collection of child nodes that match the specified type.

The collection of nodes returned by this method is always live.

A live collection is always in sync with the document. For example, if you selected all sections in a document and enumerate through the collection deleting the sections, the section is removed from the collection immediately when it is removed from the document.

Parameters
nodeTypeSpecifies the type of nodes to select.
isDeepTrue to select from all child nodes recursively. False to select only among immediate children.
Returns
A live collection of child nodes of the specified type.
Examples

Shows how to get all comments with all replies.

auto doc = MakeObject<Document>(MyDir + u"Comments.docx");
// Get all comment from the document
SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
// For all comments and replies we identify comment level and info about it
for (auto comment : System::IterateOver(comments->LINQ_OfType<SharedPtr<Comment> >()))
{
if (comment->get_Ancestor() == nullptr)
{
System::Console::WriteLine(u"\nThis is a top-level comment");
System::Console::WriteLine(String(u"Comment author: ") + comment->get_Author());
System::Console::WriteLine(String(u"Comment text: ") + comment->GetText());
for (auto commentReply : System::IterateOver(comment->get_Replies()->LINQ_OfType<SharedPtr<Comment> >()))
{
System::Console::WriteLine(u"\n\tThis is a comment reply");
System::Console::WriteLine(String(u"\tReply author: ") + commentReply->get_Author());
System::Console::WriteLine(String(u"\tReply text: ") + commentReply->GetText());
}
}
}

Shows how to extract images from a document and save them as files.

auto doc = MakeObject<Document>(MyDir + u"Images.docx");
SharedPtr<NodeCollection> shapes = doc->GetChildNodes(NodeType::Shape, true);
ASSERT_EQ(9, shapes->LINQ_Count([](SharedPtr<Node> s) { return (System::DynamicCast<Shape>(s))->get_HasImage(); }));
int imageIndex = 0;
for (auto shape : System::IterateOver(shapes->LINQ_OfType<SharedPtr<Shape> >()))
{
if (shape->get_HasImage())
{
String imageFileName = String::Format(u"File.ExtractImagesToFiles.{0}{1}", imageIndex, FileFormatUtil::ImageTypeToExtension(shape->get_ImageData()->get_ImageType()));
shape->get_ImageData()->Save(ArtifactsDir + imageFileName);
imageIndex++;
}
}

Shows how to add, update and delete child nodes from a CompositeNode's child collection.

auto doc = MakeObject<Document>();
// An empty document has one paragraph by default
ASSERT_EQ(1, doc->get_FirstSection()->get_Body()->get_Paragraphs()->get_Count());
// A paragraph is a composite node because it can contain runs, which are another type of node
SharedPtr<Paragraph> paragraph = doc->get_FirstSection()->get_Body()->get_FirstParagraph();
auto paragraphText = MakeObject<Run>(doc, u"Initial text. ");
paragraph->AppendChild(paragraphText);
// We will place these 3 children into the main text of our paragraph
auto run1 = MakeObject<Run>(doc, u"Run 1. ");
auto run2 = MakeObject<Run>(doc, u"Run 2. ");
auto run3 = MakeObject<Run>(doc, u"Run 3. ");
// We initialized them but not in our paragraph yet
ASSERT_EQ(u"Initial text.", paragraph->GetText().Trim());
// Insert run2 before initial paragraph text. This will be at the start of the paragraph
paragraph->InsertBefore(run2, paragraphText);
// Insert run3 after initial paragraph text. This will be at the end of the paragraph
paragraph->InsertAfter(run3, paragraphText);
// Insert run1 before every other child node. run2 was the start of the paragraph, now it will be run1
paragraph->PrependChild(run1);
ASSERT_EQ(u"Run 1. Run 2. Initial text. Run 3.", paragraph->GetText().Trim());
ASSERT_EQ(4, paragraph->GetChildNodes(NodeType::Any, true)->get_Count());
// Access the child node collection and update/delete children
(System::DynamicCast<Run>(paragraph->GetChildNodes(NodeType::Run, true)->idx_get(1)))->set_Text(u"Updated run 2. ");
paragraph->GetChildNodes(NodeType::Run, true)->Remove(paragraphText);
ASSERT_EQ(u"Run 1. Updated run 2. Run 3.", paragraph->GetText().Trim());
ASSERT_EQ(3, paragraph->GetChildNodes(NodeType::Any, true)->get_Count());

◆ GetCurrentNode()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::GetCurrentNode ( )
override

◆ GetEnumerator()

System::SharedPtr<System::Collections::Generic::IEnumerator<System::SharedPtr<Aspose::Words::Node> > > Aspose::Words::CompositeNode::GetEnumerator ( )
overridevirtual

Provides support for the for each style iteration over the child nodes of this node.

Examples

Shows how to enumerate immediate children of a CompositeNode using the enumerator provided by the ChildNodes collection.

auto doc = MakeObject<Document>();
auto paragraph = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 0, true));
paragraph->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
paragraph->AppendChild(MakeObject<Run>(doc, u" Hello again!"));
SharedPtr<NodeCollection> children = paragraph->get_ChildNodes();
// Paragraph may contain children of various types such as runs, shapes and so on
for (auto child : System::IterateOver(children))
{
if (child->get_NodeType() == NodeType::Run)
{
auto run = System::DynamicCast<Run>(child);
System::Console::WriteLine(run->get_Text());
}
}

Implements System::Collections::Generic::IEnumerable< System::SharedPtr< Aspose::Words::Node > >.

◆ GetNextMatchingNode()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::GetNextMatchingNode ( System::SharedPtr< Aspose::Words::Node curNode)
override

◆ GetText()

System::String Aspose::Words::CompositeNode::GetText ( )
overridevirtual

Gets the text of this node and of all its children.

The returned string includes all control and special characters as described in ControlChar.

Examples

Shows the difference between calling the GetText and ToString methods on a node.

auto doc = MakeObject<Document>();
// Enter a field into the document
auto builder = MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD Field");
// GetText will retrieve all field codes and special characters
ASSERT_EQ(u"\u0013MERGEFIELD Field\u0014«Field»\u0015\u000c", doc->GetText());
// ToString will give us the plaintext version of the document in the save format we put into the parameter
ASSERT_EQ(u"«Field»\r\n", doc->ToString(SaveFormat::Text));

Shows how to output all paragraphs in a document that are bulleted or numbered.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->get_ListFormat()->ApplyNumberDefault();
builder->Writeln(u"Numbered list item 1");
builder->Writeln(u"Numbered list item 2");
builder->Writeln(u"Numbered list item 3");
builder->get_ListFormat()->RemoveNumbers();
builder->get_ListFormat()->ApplyBulletDefault();
builder->Writeln(u"Bulleted list item 1");
builder->Writeln(u"Bulleted list item 2");
builder->Writeln(u"Bulleted list item 3");
builder->get_ListFormat()->RemoveNumbers();
SharedPtr<NodeCollection> paras = doc->GetChildNodes(NodeType::Paragraph, true);
for (auto para : System::IterateOver(paras->LINQ_OfType<SharedPtr<Paragraph>>()->LINQ_Where([](SharedPtr<Paragraph> p) { return p->get_ListFormat()->get_IsListItem(); })))
{
System::Console::WriteLine(String::Format(u"This paragraph belongs to list ID# {0}, number style \"{1}\"", para->get_ListFormat()->get_List()->get_ListId(), para->get_ListFormat()->get_ListLevel()->get_NumberStyle()));
System::Console::WriteLine(String::Format(u"\t\"{0}\"", para->GetText().Trim()));
}

Reimplemented from Aspose::Words::Node.

Reimplemented in Aspose::Words::Paragraph, and Aspose::Words::Tables::Row.

◆ GetType()

◆ IndexOf()

int32_t Aspose::Words::CompositeNode::IndexOf ( System::SharedPtr< Aspose::Words::Node child)

Returns the index of the specified child node in the child node array.

Examples

Shows how to get the index of a given child node from its parent.

auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
// Get the body of the first section in the document
SharedPtr<Body> body = doc->get_FirstSection()->get_Body();
// Retrieve the index of the last paragraph in the body
ASSERT_EQ(24, body->get_ChildNodes()->IndexOf(body->get_LastParagraph()));

◆ InsertAfter()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::InsertAfter ( System::SharedPtr< Aspose::Words::Node newChild,
System::SharedPtr< Aspose::Words::Node refChild 
)

Inserts the specified node immediately after the specified reference node.

If refChild is null, inserts newChild at the beginning of the list of child nodes.

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 ImportNode() to import the node to the current document. The imported node can then be inserted into the current document.

Parameters
newChildThe Node to insert.
refChildThe Node that is the reference node. The newNode is placed after the refNode.
Returns
The inserted node.
Examples

Shows how to add, update and delete child nodes from a CompositeNode's child collection.

auto doc = MakeObject<Document>();
// An empty document has one paragraph by default
ASSERT_EQ(1, doc->get_FirstSection()->get_Body()->get_Paragraphs()->get_Count());
// A paragraph is a composite node because it can contain runs, which are another type of node
SharedPtr<Paragraph> paragraph = doc->get_FirstSection()->get_Body()->get_FirstParagraph();
auto paragraphText = MakeObject<Run>(doc, u"Initial text. ");
paragraph->AppendChild(paragraphText);
// We will place these 3 children into the main text of our paragraph
auto run1 = MakeObject<Run>(doc, u"Run 1. ");
auto run2 = MakeObject<Run>(doc, u"Run 2. ");
auto run3 = MakeObject<Run>(doc, u"Run 3. ");
// We initialized them but not in our paragraph yet
ASSERT_EQ(u"Initial text.", paragraph->GetText().Trim());
// Insert run2 before initial paragraph text. This will be at the start of the paragraph
paragraph->InsertBefore(run2, paragraphText);
// Insert run3 after initial paragraph text. This will be at the end of the paragraph
paragraph->InsertAfter(run3, paragraphText);
// Insert run1 before every other child node. run2 was the start of the paragraph, now it will be run1
paragraph->PrependChild(run1);
ASSERT_EQ(u"Run 1. Run 2. Initial text. Run 3.", paragraph->GetText().Trim());
ASSERT_EQ(4, paragraph->GetChildNodes(NodeType::Any, true)->get_Count());
// Access the child node collection and update/delete children
(System::DynamicCast<Run>(paragraph->GetChildNodes(NodeType::Run, true)->idx_get(1)))->set_Text(u"Updated run 2. ");
paragraph->GetChildNodes(NodeType::Run, true)->Remove(paragraphText);
ASSERT_EQ(u"Run 1. Updated run 2. Run 3.", paragraph->GetText().Trim());
ASSERT_EQ(3, paragraph->GetChildNodes(NodeType::Any, true)->get_Count());

Shows how to replace all textboxes with images.

auto doc = MakeObject<Document>(MyDir + u"Textboxes in drawing canvas.docx");
// This gets a live collection of all shape nodes in the document
SharedPtr<NodeCollection> shapeCollection = doc->GetChildNodes(NodeType::Shape, true);
// Since we will be adding/removing nodes, it is better to copy all collection
// into a fixed size array, otherwise iterator will be invalidated
ArrayPtr<SharedPtr<Node>> shapes = shapeCollection->ToArray();
for (auto shape : System::IterateOver(shapes->LINQ_OfType<SharedPtr<Shape> >()))
{
// Filter out all shapes that we don't need
if (System::ObjectExt::Equals(shape->get_ShapeType(), ShapeType::TextBox))
{
// Create a new shape that will replace the existing shape
auto image = MakeObject<Shape>(doc, ShapeType::Image);
// Load the image into the new shape
image->get_ImageData()->SetImage(ImageDir + u"Windows MetaFile.wmf");
// Make new shape's position to match the old shape
image->set_Left(shape->get_Left());
image->set_Top(shape->get_Top());
image->set_Width(shape->get_Width());
image->set_Height(shape->get_Height());
image->set_RelativeHorizontalPosition(shape->get_RelativeHorizontalPosition());
image->set_RelativeVerticalPosition(shape->get_RelativeVerticalPosition());
image->set_HorizontalAlignment(shape->get_HorizontalAlignment());
image->set_VerticalAlignment(shape->get_VerticalAlignment());
image->set_WrapType(shape->get_WrapType());
image->set_WrapSide(shape->get_WrapSide());
// Insert new shape after the old shape and remove the old shape
shape->get_ParentNode()->InsertAfter(image, shape);
shape->Remove();
}
}
doc->Save(ArtifactsDir + u"Shape.ReplaceTextboxesWithImages.docx");

◆ InsertBefore()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::InsertBefore ( System::SharedPtr< Aspose::Words::Node newChild,
System::SharedPtr< Aspose::Words::Node refChild 
)

Inserts the specified node immediately before the specified reference node.

If refChild is null, inserts newChild at the end of the list of child nodes.

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 ImportNode() to import the node to the current document. The imported node can then be inserted into the current document.

Parameters
newChildThe Node to insert.
refChildThe Node that is the reference node. The newChild is placed before this node.
Returns
The inserted node.
Examples

Shows how to add, update and delete child nodes from a CompositeNode's child collection.

auto doc = MakeObject<Document>();
// An empty document has one paragraph by default
ASSERT_EQ(1, doc->get_FirstSection()->get_Body()->get_Paragraphs()->get_Count());
// A paragraph is a composite node because it can contain runs, which are another type of node
SharedPtr<Paragraph> paragraph = doc->get_FirstSection()->get_Body()->get_FirstParagraph();
auto paragraphText = MakeObject<Run>(doc, u"Initial text. ");
paragraph->AppendChild(paragraphText);
// We will place these 3 children into the main text of our paragraph
auto run1 = MakeObject<Run>(doc, u"Run 1. ");
auto run2 = MakeObject<Run>(doc, u"Run 2. ");
auto run3 = MakeObject<Run>(doc, u"Run 3. ");
// We initialized them but not in our paragraph yet
ASSERT_EQ(u"Initial text.", paragraph->GetText().Trim());
// Insert run2 before initial paragraph text. This will be at the start of the paragraph
paragraph->InsertBefore(run2, paragraphText);
// Insert run3 after initial paragraph text. This will be at the end of the paragraph
paragraph->InsertAfter(run3, paragraphText);
// Insert run1 before every other child node. run2 was the start of the paragraph, now it will be run1
paragraph->PrependChild(run1);
ASSERT_EQ(u"Run 1. Run 2. Initial text. Run 3.", paragraph->GetText().Trim());
ASSERT_EQ(4, paragraph->GetChildNodes(NodeType::Any, true)->get_Count());
// Access the child node collection and update/delete children
(System::DynamicCast<Run>(paragraph->GetChildNodes(NodeType::Run, true)->idx_get(1)))->set_Text(u"Updated run 2. ");
paragraph->GetChildNodes(NodeType::Run, true)->Remove(paragraphText);
ASSERT_EQ(u"Run 1. Updated run 2. Run 3.", paragraph->GetText().Trim());
ASSERT_EQ(3, paragraph->GetChildNodes(NodeType::Any, true)->get_Count());

◆ Is()

◆ PrependChild()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::PrependChild ( System::SharedPtr< Aspose::Words::Node newChild)

Adds the specified node to the beginning of the list of child nodes for this node.

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 ImportNode() to import the node to the current document. The imported node can then be inserted into the current document.

Parameters
newChildThe node to add.
Returns
The node added.
Examples

Shows how to add, update and delete child nodes from a CompositeNode's child collection.

auto doc = MakeObject<Document>();
// An empty document has one paragraph by default
ASSERT_EQ(1, doc->get_FirstSection()->get_Body()->get_Paragraphs()->get_Count());
// A paragraph is a composite node because it can contain runs, which are another type of node
SharedPtr<Paragraph> paragraph = doc->get_FirstSection()->get_Body()->get_FirstParagraph();
auto paragraphText = MakeObject<Run>(doc, u"Initial text. ");
paragraph->AppendChild(paragraphText);
// We will place these 3 children into the main text of our paragraph
auto run1 = MakeObject<Run>(doc, u"Run 1. ");
auto run2 = MakeObject<Run>(doc, u"Run 2. ");
auto run3 = MakeObject<Run>(doc, u"Run 3. ");
// We initialized them but not in our paragraph yet
ASSERT_EQ(u"Initial text.", paragraph->GetText().Trim());
// Insert run2 before initial paragraph text. This will be at the start of the paragraph
paragraph->InsertBefore(run2, paragraphText);
// Insert run3 after initial paragraph text. This will be at the end of the paragraph
paragraph->InsertAfter(run3, paragraphText);
// Insert run1 before every other child node. run2 was the start of the paragraph, now it will be run1
paragraph->PrependChild(run1);
ASSERT_EQ(u"Run 1. Run 2. Initial text. Run 3.", paragraph->GetText().Trim());
ASSERT_EQ(4, paragraph->GetChildNodes(NodeType::Any, true)->get_Count());
// Access the child node collection and update/delete children
(System::DynamicCast<Run>(paragraph->GetChildNodes(NodeType::Run, true)->idx_get(1)))->set_Text(u"Updated run 2. ");
paragraph->GetChildNodes(NodeType::Run, true)->Remove(paragraphText);
ASSERT_EQ(u"Run 1. Updated run 2. Run 3.", paragraph->GetText().Trim());
ASSERT_EQ(3, paragraph->GetChildNodes(NodeType::Any, true)->get_Count());

◆ RemoveAllChildren()

void Aspose::Words::CompositeNode::RemoveAllChildren ( )

Removes all the child nodes of the current node.

Examples

Shows how to construct an Aspose Words document node by node.

auto doc = MakeObject<Document>();
// A newly created blank document still comes one section, one body and one paragraph
// Calling this method will remove all those nodes to completely empty the document
doc->RemoveAllChildren();
// This document now has no composite nodes that content can be added to
// If we wish to edit it, we will need to repopulate its node collection,
// which we will start to do with by creating a new Section node
auto section = MakeObject<Section>(doc);
// Append the section to the document
doc->AppendChild(section);
// Lets set some properties for the section
section->get_PageSetup()->set_SectionStart(SectionStart::NewPage);
section->get_PageSetup()->set_PaperSize(PaperSize::Letter);
// The section that we created is empty, lets populate it. The section needs at least the Body node
auto body = MakeObject<Body>(doc);
section->AppendChild(body);
// The body needs to have at least one paragraph
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information
auto para = MakeObject<Paragraph>(doc);
body->AppendChild(para);
// We can set some formatting for the paragraph
para->get_ParagraphFormat()->set_StyleName(u"Heading 1");
para->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
// So far we have one empty paragraph in the document
// The document is valid and can be saved, but lets add some text before saving
// Create a new run of text and add it to our paragraph
auto run = MakeObject<Run>(doc);
run->set_Text(u"Hello World!");
run->get_Font()->set_Color(System::Drawing::Color::get_Red());
para->AppendChild(run);
ASSERT_EQ(String(u"Hello World!") + ControlChar::SectionBreakChar, doc->GetText());
doc->Save(ArtifactsDir + u"Section.CreateFromScratch.docx");

◆ RemoveChild()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::RemoveChild ( System::SharedPtr< Aspose::Words::Node oldChild)

Removes the specified child node.

The parent of oldChild is set to null after the node is removed.

Parameters
oldChildThe node to remove.
Returns
The removed node.
Examples

Shows how to use of methods of Node and CompositeNode to remove a section before the last section in the document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a second section by inserting a section break and add text to both sections
builder->Writeln(u"Section 1 text.");
builder->InsertBreak(BreakType::SectionBreakContinuous);
builder->Writeln(u"Section 2 text.");
// Both sections are siblings of each other
auto lastSection = System::DynamicCast<Section>(doc->get_LastChild());
auto firstSection = System::DynamicCast<Section>(lastSection->get_PreviousSibling());
// Remove a section based on its sibling relationship with another section
if (lastSection->get_PreviousSibling() != nullptr)
{
doc->RemoveChild(firstSection);
}
// The section we removed was the first one, leaving the document with only the second
ASSERT_EQ(u"Section 2 text.", doc->GetText().Trim());

◆ RemoveSmartTags()

void Aspose::Words::CompositeNode::RemoveSmartTags ( )

Removes all SmartTag descendant nodes of the current node.

Examples

Removes all smart tags from descendant nodes of the composite node.

auto doc = MakeObject<Document>(MyDir + u"Smart tags.doc");
ASSERT_EQ(8, doc->GetChildNodes(NodeType::SmartTag, true)->get_Count());
// Remove smart tags from the whole document
doc->RemoveSmartTags();
ASSERT_EQ(0, doc->GetChildNodes(NodeType::SmartTag, true)->get_Count());

◆ SelectNodes()

System::SharedPtr<Aspose::Words::NodeList> Aspose::Words::CompositeNode::SelectNodes ( System::String  xpath)

Selects a list of nodes matching the XPath expression.

Only expressions with element names are supported at the moment. Expressions that use attribute names are not supported.

Parameters
xpathThe XPath expression.
Returns
A list of nodes matching the XPath query.

◆ SelectSingleNode()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::CompositeNode::SelectSingleNode ( System::String  xpath)

Selects the first Node that matches the XPath expression.

Only expressions with element names are supported at the moment. Expressions that use attribute names are not supported.

Parameters
xpathThe XPath expression.
Returns
The first Node that matches the XPath query or null if no matching node is found.

◆ Type()

static const System::TypeInfo& Aspose::Words::CompositeNode::Type ( )
static
@ Comment
A comment in a Word document. A Comment node can have Paragraph and Table nodes.
String
@ Shape
A drawing object, such as an OfficeArt shape, image or an OLE object. A Shape node can contain Paragr...
@ SmartTag
A smart tag around one or more inline structures (runs, images, fields,etc.) within a paragraph.
static constexpr char16_t SectionBreakChar
End of section character: (char)12 or "\f".
Definition: ControlChar.h:1253
@ Text
Saves the document in the plain text format.
static ASPOSECPP_SHARED_API void WriteLine()
std::enable_if_t<!Details::IsIterable< Enumerable >::value, Details::EnumeratorAdapter< Enumerable, T > > IterateOver(System::SmartPtr< Enumerable > enumerable)
@ Letter
8.5 x 11 inches.
@ NewPage
The section starts from a new page.
static System::String NodeTypeToString(Aspose::Words::NodeType nodeType)
A utility method that converts a node type enum value into a user friendly string.
static System::String ImageTypeToExtension(Aspose::Words::Drawing::ImageType imageType)
Converts an Aspose.Words image type enumerated value into a file extension. The returned extension is...
static ASPOSECPP_SHARED_API Color get_Red()
@ Run
A run of text.
@ Paragraph
A paragraph of text. A Paragraph node is a container for inline level elements Run,...
@ Table
A Table object that represents a table in a Word document. A Table node can have Row nodes.
@ SectionBreakContinuous
Specifies start of new section on the same page as the previous section.
@ Any
Indicates all node types. Allows to select all children.
static std::enable_if< IsExceptionWrapper< T >::value, bool >::type Equals(const T &obj, const T2 &another)
@ Center
Text is centered horizontally.