Aspose::Words::Node Class Referenceabstract

Detailed Description

Base class for all nodes of a Word document.

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

For more info see the Composite design pattern.

The Node class:

  • Defines the child node interface.
  • Defines the interface for visiting nodes.
  • Provides default cloning capability.
  • Implements parent node and owner document mechanisms.
  • Implements access to sibling nodes.
Examples

Shows how to clone a composite node.

auto doc = MakeObject<Document>();
SharedPtr<Paragraph> para = doc->get_FirstSection()->get_Body()->get_FirstParagraph();
para->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
// Below are two ways of cloning a composite node.
// 1 - Create a clone of a node, and create a clone of each of its child nodes as well.
SharedPtr<Node> cloneWithChildren = para->Clone(true);
ASSERT_TRUE((System::DynamicCast<CompositeNode>(cloneWithChildren))->get_HasChildNodes());
ASSERT_EQ(u"Hello world!", cloneWithChildren->GetText().Trim());
// 2 - Create a clone of a node just by itself without any children.
SharedPtr<Node> cloneWithoutChildren = para->Clone(false);
ASSERT_FALSE((System::DynamicCast<CompositeNode>(cloneWithoutChildren))->get_HasChildNodes());
ASSERT_EQ(String::Empty, cloneWithoutChildren->GetText().Trim());

Shows how to traverse through a composite node's collection of child nodes.

auto doc = MakeObject<Document>();
// Add two runs and one shape as child nodes to the first paragraph of this document.
auto paragraph = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 0, true));
paragraph->AppendChild(MakeObject<Run>(doc, u"Hello world! "));
auto shape = MakeObject<Shape>(doc, ShapeType::Rectangle);
shape->set_Width(200);
shape->set_Height(200);
// Note that the 'CustomNodeId' is not saved to an output file and exists only during the node lifetime.
shape->set_CustomNodeId(100);
shape->set_WrapType(WrapType::Inline);
paragraph->AppendChild(shape);
paragraph->AppendChild(MakeObject<Run>(doc, u"Hello again!"));
// Iterate through the paragraph's collection of immediate children,
// and print any runs or shapes that we find within.
SharedPtr<NodeCollection> children = paragraph->get_ChildNodes();
ASSERT_EQ(3, paragraph->get_ChildNodes()->get_Count());
for (const auto& child : System::IterateOver(children))
{
switch (child->get_NodeType())
{
std::cout << "Run contents:" << std::endl;
std::cout << "\t\"" << child->GetText().Trim() << "\"" << std::endl;
break;
auto childShape = System::DynamicCast<Shape>(child);
std::cout << "Shape:" << std::endl;
std::cout << String::Format(u"\t{0}, {1}x{2}", childShape->get_ShapeType(), childShape->get_Width(), childShape->get_Height()) << std::endl;
ASSERT_EQ(100, shape->get_CustomNodeId());
break;
}
default:
break;
}
}

Shows how to remove all child nodes of a specific type from a composite node.

auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
ASSERT_EQ(2, doc->GetChildNodes(NodeType::Table, true)->get_Count());
SharedPtr<Node> curNode = doc->get_FirstSection()->get_Body()->get_FirstChild();
while (curNode != nullptr)
{
// Save the next sibling node as a variable in case we want to move to it after deleting this node.
SharedPtr<Node> nextNode = curNode->get_NextSibling();
// A section body can contain Paragraph and Table nodes.
// If the node is a Table, remove it from the parent.
if (curNode->get_NodeType() == NodeType::Table)
{
curNode->Remove();
}
curNode = nextNode;
}
ASSERT_EQ(0, doc->GetChildNodes(NodeType::Table, true)->get_Count());

#include <Aspose.Words.Cpp/Node.h>

+ Inheritance diagram for Aspose::Words::Node:

Public Member Functions

virtual bool Accept (SharedPtr< DocumentVisitor > visitor)=0
 Accepts a visitor. More...
 
SharedPtr< NodeClone (bool isCloneChildren)
 Creates a duplicate of the node. More...
 
int32_t get_CustomNodeId () const
 Specifies custom node identifier. More...
 
virtual SharedPtr< DocumentBaseget_Document () const
 Gets the document to which this node belongs. More...
 
virtual bool get_IsComposite ()
 Returns true if this node can contain other nodes. 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 ()
 
virtual String GetText ()
 Gets the text of this node and of all its children. More...
 
virtual const TypeInfoGetType () const override
 
virtual bool Is (const TypeInfo &target) const override
 
SharedPtr< NodeNextPreOrder (const SharedPtr< Node > &rootNode)
 Gets next node according to the pre-order tree traversal algorithm. More...
 
SharedPtr< NodePreviousPreOrder (const SharedPtr< Node > &rootNode)
 Gets the previous node according to the pre-order tree traversal algorithm. More...
 
void Remove ()
 Removes itself from the parent. More...
 
void set_CustomNodeId (int32_t value)
 Setter for get_CustomNodeId. More...
 
String ToString (SaveFormat saveFormat)
 Exports the content of the node into a string in the specified format. More...
 
String ToString (const SharedPtr< SaveOptions > &saveOptions)
 Exports the content of the node into a string using the specified save options. More...
 

Static Public Member Functions

static String NodeTypeToString (NodeType nodeType)
 A utility method that converts a node type enum value into a user friendly string. More...
 
static const TypeInfoType ()
 

Member Function Documentation

◆ Accept()

virtual bool Aspose::Words::Node::Accept ( System::SharedPtr< Aspose::Words::DocumentVisitor visitor)
pure virtual

Accepts a visitor.

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Parameters
visitorThe visitor that will visit the nodes.
Returns
True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.
Examples

Shows how to use a DocumentVisitor implementation to remove all hidden content from a document.

void RemoveHiddenContentFromDocument()
{
auto doc = MakeObject<Document>(MyDir + u"Hidden content.docx");
auto hiddenContentRemover = MakeObject<ExFont::RemoveHiddenContentVisitor>();
// Below are three types of fields which can accept a document visitor,
// which will allow it to visit the accepting node, and then traverse its child nodes in a depth-first manner.
// 1 - Paragraph node:
auto para = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 4, true));
para->Accept(hiddenContentRemover);
// 2 - Table node:
SharedPtr<Table> table = doc->get_FirstSection()->get_Body()->get_Tables()->idx_get(0);
table->Accept(hiddenContentRemover);
// 3 - Document node:
doc->Accept(hiddenContentRemover);
doc->Save(ArtifactsDir + u"Font.RemoveHiddenContentFromDocument.docx");
}
class RemoveHiddenContentVisitor : public DocumentVisitor
{
public:
VisitorAction VisitFieldStart(SharedPtr<FieldStart> fieldStart) override
{
if (fieldStart->get_Font()->get_Hidden())
{
fieldStart->Remove();
}
}
VisitorAction VisitFieldEnd(SharedPtr<FieldEnd> fieldEnd) override
{
if (fieldEnd->get_Font()->get_Hidden())
{
fieldEnd->Remove();
}
}
VisitorAction VisitFieldSeparator(SharedPtr<FieldSeparator> fieldSeparator) override
{
if (fieldSeparator->get_Font()->get_Hidden())
{
fieldSeparator->Remove();
}
}
VisitorAction VisitRun(SharedPtr<Run> run) override
{
if (run->get_Font()->get_Hidden())
{
run->Remove();
}
}
VisitorAction VisitParagraphStart(SharedPtr<Paragraph> paragraph) override
{
if (paragraph->get_ParagraphBreakFont()->get_Hidden())
{
paragraph->Remove();
}
}
VisitorAction VisitFormField(SharedPtr<FormField> formField) override
{
if (formField->get_Font()->get_Hidden())
{
formField->Remove();
}
}
VisitorAction VisitGroupShapeStart(SharedPtr<GroupShape> groupShape) override
{
if (groupShape->get_Font()->get_Hidden())
{
groupShape->Remove();
}
}
VisitorAction VisitShapeStart(SharedPtr<Shape> shape) override
{
if (shape->get_Font()->get_Hidden())
{
shape->Remove();
}
}
VisitorAction VisitCommentStart(SharedPtr<Comment> comment) override
{
if (comment->get_Font()->get_Hidden())
{
comment->Remove();
}
}
VisitorAction VisitFootnoteStart(SharedPtr<Footnote> footnote) override
{
if (footnote->get_Font()->get_Hidden())
{
footnote->Remove();
}
}
VisitorAction VisitSpecialChar(SharedPtr<SpecialChar> specialChar) override
{
if (specialChar->get_Font()->get_Hidden())
{
specialChar->Remove();
}
}
VisitorAction VisitTableEnd(SharedPtr<Table> table) override
{
// The content inside table cells may have the hidden content flag, but the tables themselves cannot.
// If this table had nothing but hidden content, this visitor would have removed all of it,
// and there would be no child nodes left.
// Thus, we can also treat the table itself as hidden content and remove it.
// Tables which are empty but do not have hidden content will have cells with empty paragraphs inside,
// which this visitor will not remove.
if (!table->get_HasChildNodes())
{
table->Remove();
}
}
VisitorAction VisitCellEnd(SharedPtr<Cell> cell) override
{
if (!cell->get_HasChildNodes() && cell->get_ParentNode() != nullptr)
{
cell->Remove();
}
}
VisitorAction VisitRowEnd(SharedPtr<Row> row) override
{
if (!row->get_HasChildNodes() && row->get_ParentNode() != nullptr)
{
row->Remove();
}
}
};

Implemented in Aspose::Words::Tables::Table, Aspose::Words::Tables::Row, Aspose::Words::Tables::Cell, Aspose::Words::SubDocument, Aspose::Words::SpecialChar, Aspose::Words::Section, Aspose::Words::Run, Aspose::Words::Paragraph, Aspose::Words::Notes::Footnote, Aspose::Words::Math::OfficeMath, Aspose::Words::Markup::StructuredDocumentTagRangeStart, Aspose::Words::Markup::StructuredDocumentTagRangeEnd, Aspose::Words::Markup::StructuredDocumentTag, Aspose::Words::Markup::SmartTag, Aspose::Words::HeaderFooter, Aspose::Words::Fields::FormField, Aspose::Words::Fields::FieldStart, Aspose::Words::Fields::FieldSeparator, Aspose::Words::Fields::FieldEnd, Aspose::Words::EditableRangeStart, Aspose::Words::EditableRangeEnd, Aspose::Words::Drawing::Shape, Aspose::Words::Drawing::GroupShape, Aspose::Words::Document, Aspose::Words::CommentRangeStart, Aspose::Words::CommentRangeEnd, Aspose::Words::Comment, Aspose::Words::BuildingBlocks::GlossaryDocument, Aspose::Words::BuildingBlocks::BuildingBlock, Aspose::Words::BookmarkStart, Aspose::Words::BookmarkEnd, Aspose::Words::Body, and Aspose::Words::AbsolutePositionTab.

◆ Clone()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::Node::Clone ( bool  isCloneChildren)

Creates a duplicate of the node.

This method serves as a copy constructor for nodes. The cloned node has no parent, but belongs to the same document as the original node.

This method always performs a deep copy of the node. The isCloneChildren parameter specifies whether to perform copy all child nodes as well.

Parameters
isCloneChildrenTrue to recursively clone the subtree under the specified node; false to clone only the node itself.
Returns
The cloned node.
Examples

Shows how to clone a composite node.

auto doc = MakeObject<Document>();
SharedPtr<Paragraph> para = doc->get_FirstSection()->get_Body()->get_FirstParagraph();
para->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
// Below are two ways of cloning a composite node.
// 1 - Create a clone of a node, and create a clone of each of its child nodes as well.
SharedPtr<Node> cloneWithChildren = para->Clone(true);
ASSERT_TRUE((System::DynamicCast<CompositeNode>(cloneWithChildren))->get_HasChildNodes());
ASSERT_EQ(u"Hello world!", cloneWithChildren->GetText().Trim());
// 2 - Create a clone of a node just by itself without any children.
SharedPtr<Node> cloneWithoutChildren = para->Clone(false);
ASSERT_FALSE((System::DynamicCast<CompositeNode>(cloneWithoutChildren))->get_HasChildNodes());
ASSERT_EQ(String::Empty, cloneWithoutChildren->GetText().Trim());

◆ get_CustomNodeId()

int32_t Aspose::Words::Node::get_CustomNodeId ( ) const

Specifies custom node identifier.

Default is zero.

This identifier can be set and used arbitrarily. For example, as a key to get external data.

Important note, specified value is not saved to an output file and exists only during the node lifetime.

Examples

Shows how to traverse through a composite node's collection of child nodes.

auto doc = MakeObject<Document>();
// Add two runs and one shape as child nodes to the first paragraph of this document.
auto paragraph = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 0, true));
paragraph->AppendChild(MakeObject<Run>(doc, u"Hello world! "));
auto shape = MakeObject<Shape>(doc, ShapeType::Rectangle);
shape->set_Width(200);
shape->set_Height(200);
// Note that the 'CustomNodeId' is not saved to an output file and exists only during the node lifetime.
shape->set_CustomNodeId(100);
shape->set_WrapType(WrapType::Inline);
paragraph->AppendChild(shape);
paragraph->AppendChild(MakeObject<Run>(doc, u"Hello again!"));
// Iterate through the paragraph's collection of immediate children,
// and print any runs or shapes that we find within.
SharedPtr<NodeCollection> children = paragraph->get_ChildNodes();
ASSERT_EQ(3, paragraph->get_ChildNodes()->get_Count());
for (const auto& child : System::IterateOver(children))
{
switch (child->get_NodeType())
{
std::cout << "Run contents:" << std::endl;
std::cout << "\t\"" << child->GetText().Trim() << "\"" << std::endl;
break;
auto childShape = System::DynamicCast<Shape>(child);
std::cout << "Shape:" << std::endl;
std::cout << String::Format(u"\t{0}, {1}x{2}", childShape->get_ShapeType(), childShape->get_Width(), childShape->get_Height()) << std::endl;
ASSERT_EQ(100, shape->get_CustomNodeId());
break;
}
default:
break;
}
}

◆ get_Document()

virtual System::SharedPtr<Aspose::Words::DocumentBase> Aspose::Words::Node::get_Document ( ) const
virtual

Gets the document to which this node belongs.

The node always belongs to a document even if it has just been created and not yet added to the tree, or if it has been removed from the tree.

Examples

Shows how to create a node and set its owning document.

auto doc = MakeObject<Document>();
auto para = MakeObject<Paragraph>(doc);
para->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
// We have not yet appended this paragraph as a child to any composite node.
ASSERT_TRUE(para->get_ParentNode() == nullptr);
// If a node is an appropriate child node type of another composite node,
// we can attach it as a child only if both nodes have the same owner document.
// The owner document is the document we passed to the node's constructor.
// We have not attached this paragraph to the document, so the document does not contain its text.
ASPOSE_ASSERT_EQ(para->get_Document(), doc);
ASSERT_EQ(String::Empty, doc->GetText().Trim());
// Since the document owns this paragraph, we can apply one of its styles to the paragraph's contents.
para->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 1"));
// Add this node to the document, and then verify its contents.
doc->get_FirstSection()->get_Body()->AppendChild(para);
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body(), para->get_ParentNode());
ASSERT_EQ(u"Hello world!", doc->GetText().Trim());

Reimplemented in Aspose::Words::DocumentBase.

◆ get_IsComposite()

virtual bool Aspose::Words::Node::get_IsComposite ( )
virtual

Returns true if this node can contain other nodes.

Examples

Shows how to traverse a composite node's tree of child nodes.

void RecurseChildren()
{
auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
// Any node that can contain child nodes, such as the document itself, is composite.
ASSERT_TRUE(doc->get_IsComposite());
// Invoke the recursive function that will go through and print all the child nodes of a composite node.
TraverseAllNodes(doc, 0);
}
void TraverseAllNodes(SharedPtr<CompositeNode> parentNode, int depth)
{
for (SharedPtr<Node> childNode = parentNode->get_FirstChild(); childNode != nullptr; childNode = childNode->get_NextSibling())
{
std::cout << (String(u'\t', depth)) << Node::NodeTypeToString(childNode->get_NodeType());
// Recurse into the node if it is a composite node. Otherwise, print its contents if it is an inline node.
if (childNode->get_IsComposite())
{
std::cout << std::endl;
TraverseAllNodes(System::DynamicCast<CompositeNode>(childNode), depth + 1);
}
else if (System::ObjectExt::Is<Inline>(childNode))
{
std::cout << " - \"" << childNode->GetText().Trim() << "\"" << std::endl;
}
else
{
std::cout << std::endl;
}
}
}

Reimplemented in Aspose::Words::CompositeNode.

◆ get_NextSibling()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::Node::get_NextSibling ( )

Gets the node immediately following this node.

Examples

Shows how to traverse a composite node's tree of child nodes.

void RecurseChildren()
{
auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
// Any node that can contain child nodes, such as the document itself, is composite.
ASSERT_TRUE(doc->get_IsComposite());
// Invoke the recursive function that will go through and print all the child nodes of a composite node.
TraverseAllNodes(doc, 0);
}
void TraverseAllNodes(SharedPtr<CompositeNode> parentNode, int depth)
{
for (SharedPtr<Node> childNode = parentNode->get_FirstChild(); childNode != nullptr; childNode = childNode->get_NextSibling())
{
std::cout << (String(u'\t', depth)) << Node::NodeTypeToString(childNode->get_NodeType());
// Recurse into the node if it is a composite node. Otherwise, print its contents if it is an inline node.
if (childNode->get_IsComposite())
{
std::cout << std::endl;
TraverseAllNodes(System::DynamicCast<CompositeNode>(childNode), depth + 1);
}
else if (System::ObjectExt::Is<Inline>(childNode))
{
std::cout << " - \"" << childNode->GetText().Trim() << "\"" << std::endl;
}
else
{
std::cout << std::endl;
}
}
}

Shows how to use a node's NextSibling property to enumerate through its immediate children.

auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
for (SharedPtr<Node> node = doc->get_FirstSection()->get_Body()->get_FirstChild(); node != nullptr; node = node->get_NextSibling())
{
std::cout << std::endl;
std::cout << "Node type: " << Node::NodeTypeToString(node->get_NodeType()) << std::endl;
String contents = node->GetText().Trim();
std::cout << (contents == String::Empty ? u"This node contains no text" : String::Format(u"Contents: \"{0}\"", node->GetText().Trim()))
<< std::endl;
}

◆ get_NodeType()

virtual Aspose::Words::NodeType Aspose::Words::Node::get_NodeType ( ) const
pure virtual

Gets the type of this node.

Examples

Shows how to traverse a composite node's tree of child nodes.

void RecurseChildren()
{
auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
// Any node that can contain child nodes, such as the document itself, is composite.
ASSERT_TRUE(doc->get_IsComposite());
// Invoke the recursive function that will go through and print all the child nodes of a composite node.
TraverseAllNodes(doc, 0);
}
void TraverseAllNodes(SharedPtr<CompositeNode> parentNode, int depth)
{
for (SharedPtr<Node> childNode = parentNode->get_FirstChild(); childNode != nullptr; childNode = childNode->get_NextSibling())
{
std::cout << (String(u'\t', depth)) << Node::NodeTypeToString(childNode->get_NodeType());
// Recurse into the node if it is a composite node. Otherwise, print its contents if it is an inline node.
if (childNode->get_IsComposite())
{
std::cout << std::endl;
TraverseAllNodes(System::DynamicCast<CompositeNode>(childNode), depth + 1);
}
else if (System::ObjectExt::Is<Inline>(childNode))
{
std::cout << " - \"" << childNode->GetText().Trim() << "\"" << std::endl;
}
else
{
std::cout << std::endl;
}
}
}

Shows how to remove all child nodes of a specific type from a composite node.

auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
ASSERT_EQ(2, doc->GetChildNodes(NodeType::Table, true)->get_Count());
SharedPtr<Node> curNode = doc->get_FirstSection()->get_Body()->get_FirstChild();
while (curNode != nullptr)
{
// Save the next sibling node as a variable in case we want to move to it after deleting this node.
SharedPtr<Node> nextNode = curNode->get_NextSibling();
// A section body can contain Paragraph and Table nodes.
// If the node is a Table, remove it from the parent.
if (curNode->get_NodeType() == NodeType::Table)
{
curNode->Remove();
}
curNode = nextNode;
}
ASSERT_EQ(0, doc->GetChildNodes(NodeType::Table, true)->get_Count());

Shows how to use a node's NextSibling property to enumerate through its immediate children.

auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
for (SharedPtr<Node> node = doc->get_FirstSection()->get_Body()->get_FirstChild(); node != nullptr; node = node->get_NextSibling())
{
std::cout << std::endl;
std::cout << "Node type: " << Node::NodeTypeToString(node->get_NodeType()) << std::endl;
String contents = node->GetText().Trim();
std::cout << (contents == String::Empty ? u"This node contains no text" : String::Format(u"Contents: \"{0}\"", node->GetText().Trim()))
<< std::endl;
}

Implemented in Aspose::Words::Tables::Table, Aspose::Words::Tables::Row, Aspose::Words::Tables::Cell, Aspose::Words::SubDocument, Aspose::Words::SpecialChar, Aspose::Words::Section, Aspose::Words::Run, Aspose::Words::Paragraph, Aspose::Words::Notes::Footnote, Aspose::Words::Math::OfficeMath, Aspose::Words::Markup::StructuredDocumentTagRangeStart, Aspose::Words::Markup::StructuredDocumentTagRangeEnd, Aspose::Words::Markup::StructuredDocumentTag, Aspose::Words::Markup::SmartTag, Aspose::Words::HeaderFooter, Aspose::Words::Fields::FormField, Aspose::Words::Fields::FieldStart, Aspose::Words::Fields::FieldSeparator, Aspose::Words::Fields::FieldEnd, Aspose::Words::EditableRangeStart, Aspose::Words::EditableRangeEnd, Aspose::Words::Drawing::Shape, Aspose::Words::Drawing::GroupShape, Aspose::Words::Document, Aspose::Words::CommentRangeStart, Aspose::Words::CommentRangeEnd, Aspose::Words::Comment, Aspose::Words::BuildingBlocks::GlossaryDocument, Aspose::Words::BuildingBlocks::BuildingBlock, Aspose::Words::BookmarkStart, Aspose::Words::BookmarkEnd, and Aspose::Words::Body.

◆ get_ParentNode()

System::SharedPtr<Aspose::Words::CompositeNode> Aspose::Words::Node::get_ParentNode ( )

Gets the immediate parent of this node.

If a node has just been created and not yet added to the tree, or if it has been removed from the tree, the parent is null.

Examples

Shows how to access a node's parent node.

auto doc = MakeObject<Document>();
SharedPtr<Paragraph> para = doc->get_FirstSection()->get_Body()->get_FirstParagraph();
// Append a child Run node to the document's first paragraph.
auto run = MakeObject<Run>(doc, u"Hello world!");
para->AppendChild(run);
// The paragraph is the parent node of the run node. We can trace this lineage
// all the way to the document node, which is the root of the document's node tree.
ASPOSE_ASSERT_EQ(para, run->get_ParentNode());
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body(), para->get_ParentNode());
ASPOSE_ASSERT_EQ(doc->get_FirstSection(), doc->get_FirstSection()->get_Body()->get_ParentNode());
ASPOSE_ASSERT_EQ(doc, doc->get_FirstSection()->get_ParentNode());

Shows how to create a node and set its owning document.

auto doc = MakeObject<Document>();
auto para = MakeObject<Paragraph>(doc);
para->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
// We have not yet appended this paragraph as a child to any composite node.
ASSERT_TRUE(para->get_ParentNode() == nullptr);
// If a node is an appropriate child node type of another composite node,
// we can attach it as a child only if both nodes have the same owner document.
// The owner document is the document we passed to the node's constructor.
// We have not attached this paragraph to the document, so the document does not contain its text.
ASPOSE_ASSERT_EQ(para->get_Document(), doc);
ASSERT_EQ(String::Empty, doc->GetText().Trim());
// Since the document owns this paragraph, we can apply one of its styles to the paragraph's contents.
para->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 1"));
// Add this node to the document, and then verify its contents.
doc->get_FirstSection()->get_Body()->AppendChild(para);
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body(), para->get_ParentNode());
ASSERT_EQ(u"Hello world!", doc->GetText().Trim());

◆ get_PreviousSibling()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::Node::get_PreviousSibling ( )

Gets the node immediately preceding this 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);
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());

◆ get_Range()

System::SharedPtr<Aspose::Words::Range> Aspose::Words::Node::get_Range ( )

Returns a Range object that represents the portion of a document that is contained in this node.

Examples

Shows how to delete all the nodes from a range.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Add text to the first section in the document, and then add another section.
builder->Write(u"Section 1. ");
builder->InsertBreak(BreakType::SectionBreakContinuous);
builder->Write(u"Section 2.");
ASSERT_EQ(u"Section 1. \fSection 2.", doc->GetText().Trim());
// Remove the first section entirely by removing all the nodes
// within its range, including the section itself.
doc->get_Sections()->idx_get(0)->get_Range()->Delete();
ASSERT_EQ(1, doc->get_Sections()->get_Count());
ASSERT_EQ(u"Section 2.", doc->GetText().Trim());

◆ GetAncestor()

System::SharedPtr<Aspose::Words::CompositeNode> Aspose::Words::Node::GetAncestor ( Aspose::Words::NodeType  ancestorType)

Gets the first ancestor of the specified NodeType.

Parameters
ancestorTypeThe node type of the ancestor to retrieve.
Returns
The ancestor of the specified type or null if no ancestor of this type was found.
Examples

Shows how to find out if a tables are nested.

void CalculateDepthOfNestedTables()
{
auto doc = MakeObject<Document>(MyDir + u"Nested tables.docx");
SharedPtr<NodeCollection> tables = doc->GetChildNodes(NodeType::Table, true);
for (int i = 0; i < tables->get_Count(); i++)
{
auto table = System::DynamicCast<Table>(tables->idx_get(i));
// Find out if any cells in the table have other tables as children.
int count = GetChildTableCount(table);
std::cout << "Table #" << i << " has " << count << " tables directly within its cells" << std::endl;
// Find out if the table is nested inside another table, and, if so, at what depth.
int tableDepth = GetNestedDepthOfTable(table);
if (tableDepth > 0)
{
std::cout << "Table #" << i << " is nested inside another table at depth of " << tableDepth << std::endl;
}
else
{
std::cout << "Table #" << i << " is a non nested table (is not a child of another table)" << std::endl;
}
}
}
static int GetNestedDepthOfTable(SharedPtr<Table> table)
{
int depth = 0;
SharedPtr<Node> parent = table->GetAncestor(table->get_NodeType());
while (parent != nullptr)
{
depth++;
parent = parent->GetAncestorOf<SharedPtr<Table>>();
}
return depth;
}
static int GetChildTableCount(SharedPtr<Table> table)
{
int childTableCount = 0;
for (const auto& row : System::IterateOver(table->get_Rows()->LINQ_OfType<SharedPtr<Row>>()))
{
for (const auto& Cell : System::IterateOver(row->get_Cells()->LINQ_OfType<SharedPtr<Cell>>()))
{
SharedPtr<TableCollection> childTables = Cell->get_Tables();
if (childTables->get_Count() > 0)
{
childTableCount++;
}
}
}
return childTableCount;
}

◆ GetAncestorOf()

template<typename T >
T Aspose::Words::Node::GetAncestorOf ( )
inline

◆ GetText()

virtual System::String Aspose::Words::Node::GetText ( )
virtual

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 how to use control characters.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert paragraphs with text with DocumentBuilder.
builder->Writeln(u"Hello world!");
builder->Writeln(u"Hello again!");
// Converting the document to text form reveals that control characters
// represent some of the document's structural elements, such as page breaks.
ASSERT_EQ(String::Format(u"Hello world!{0}", ControlChar::Cr()) + String::Format(u"Hello again!{0}", ControlChar::Cr()) + ControlChar::PageBreak(),
doc->GetText());
// When converting a document to string form,
// we can omit some of the control characters with the Trim method.
ASSERT_EQ(String::Format(u"Hello world!{0}", ControlChar::Cr()) + u"Hello again!", doc->GetText().Trim());

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

auto doc = MakeObject<Document>();
// A blank document contains one section, one body and one paragraph.
// Call the "RemoveAllChildren" method to remove all those nodes,
// and end up with a document node with no children.
doc->RemoveAllChildren();
// This document now has no composite child nodes that we can add content to.
// If we wish to edit it, we will need to repopulate its node collection.
// First, create a new section, and then append it as a child to the root document node.
auto section = MakeObject<Section>(doc);
doc->AppendChild(section);
// Set some page setup properties for the section.
section->get_PageSetup()->set_SectionStart(SectionStart::NewPage);
section->get_PageSetup()->set_PaperSize(PaperSize::Letter);
// A section needs a body, which will contain and display all its contents
// on the page between the section's header and footer.
auto body = MakeObject<Body>(doc);
section->AppendChild(body);
// Create a paragraph, set some formatting properties, and then append it as a child to the body.
auto para = MakeObject<Paragraph>(doc);
para->get_ParagraphFormat()->set_StyleName(u"Heading 1");
para->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
body->AppendChild(para);
// Finally, add some content to do the document. Create a run,
// set its appearance and contents, and then append it as a child to the 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(u"Hello World!", doc->GetText().Trim());
doc->Save(ArtifactsDir + u"Section.CreateManually.docx");

Reimplemented in Aspose::Words::Tables::Row, Aspose::Words::SpecialChar, Aspose::Words::Run, Aspose::Words::Paragraph, Aspose::Words::CompositeNode, and Aspose::Words::BookmarkStart.

◆ GetType()

◆ Is()

◆ NextPreOrder()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::Node::NextPreOrder ( const System::SharedPtr< Aspose::Words::Node > &  rootNode)

Gets next node according to the pre-order tree traversal algorithm.

Parameters
rootNodeThe top node (limit) of traversal.
Returns
Next node in pre-order order. Null if reached the rootNode.
Examples

Shows how to traverse the document's node tree using the pre-order traversal algorithm, and delete any encountered shape with an image.

auto doc = MakeObject<Document>(MyDir + u"Images.docx");
ASSERT_EQ(9,
doc->GetChildNodes(NodeType::Shape, true)->LINQ_OfType<SharedPtr<Shape>>()->LINQ_Count([](SharedPtr<Shape> s) { return s->get_HasImage(); }));
SharedPtr<Node> curNode = doc;
while (curNode != nullptr)
{
SharedPtr<Node> nextNode = curNode->NextPreOrder(doc);
if (curNode->PreviousPreOrder(doc) != nullptr && nextNode != nullptr)
{
ASPOSE_ASSERT_EQ(curNode, nextNode->PreviousPreOrder(doc));
}
if (curNode->get_NodeType() == NodeType::Shape && (System::DynamicCast<Shape>(curNode))->get_HasImage())
{
curNode->Remove();
}
curNode = nextNode;
}
ASSERT_EQ(0,
doc->GetChildNodes(NodeType::Shape, true)->LINQ_OfType<SharedPtr<Shape>>()->LINQ_Count([](SharedPtr<Shape> s) { return s->get_HasImage(); }));

◆ NodeTypeToString()

static System::String Aspose::Words::Node::NodeTypeToString ( Aspose::Words::NodeType  nodeType)
static

A utility method that converts a node type enum value into a user friendly string.

Examples

Shows how to traverse a composite node's tree of child nodes.

void RecurseChildren()
{
auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
// Any node that can contain child nodes, such as the document itself, is composite.
ASSERT_TRUE(doc->get_IsComposite());
// Invoke the recursive function that will go through and print all the child nodes of a composite node.
TraverseAllNodes(doc, 0);
}
void TraverseAllNodes(SharedPtr<CompositeNode> parentNode, int depth)
{
for (SharedPtr<Node> childNode = parentNode->get_FirstChild(); childNode != nullptr; childNode = childNode->get_NextSibling())
{
std::cout << (String(u'\t', depth)) << Node::NodeTypeToString(childNode->get_NodeType());
// Recurse into the node if it is a composite node. Otherwise, print its contents if it is an inline node.
if (childNode->get_IsComposite())
{
std::cout << std::endl;
TraverseAllNodes(System::DynamicCast<CompositeNode>(childNode), depth + 1);
}
else if (System::ObjectExt::Is<Inline>(childNode))
{
std::cout << " - \"" << childNode->GetText().Trim() << "\"" << std::endl;
}
else
{
std::cout << std::endl;
}
}
}

Shows how to use a node's NextSibling property to enumerate through its immediate children.

auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
for (SharedPtr<Node> node = doc->get_FirstSection()->get_Body()->get_FirstChild(); node != nullptr; node = node->get_NextSibling())
{
std::cout << std::endl;
std::cout << "Node type: " << Node::NodeTypeToString(node->get_NodeType()) << std::endl;
String contents = node->GetText().Trim();
std::cout << (contents == String::Empty ? u"This node contains no text" : String::Format(u"Contents: \"{0}\"", node->GetText().Trim()))
<< std::endl;
}

◆ PreviousPreOrder()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::Node::PreviousPreOrder ( const System::SharedPtr< Aspose::Words::Node > &  rootNode)

Gets the previous node according to the pre-order tree traversal algorithm.

Parameters
rootNodeThe top node (limit) of traversal.
Returns
Previous node in pre-order order. Null if reached the rootNode.
Examples

Shows how to traverse the document's node tree using the pre-order traversal algorithm, and delete any encountered shape with an image.

auto doc = MakeObject<Document>(MyDir + u"Images.docx");
ASSERT_EQ(9,
doc->GetChildNodes(NodeType::Shape, true)->LINQ_OfType<SharedPtr<Shape>>()->LINQ_Count([](SharedPtr<Shape> s) { return s->get_HasImage(); }));
SharedPtr<Node> curNode = doc;
while (curNode != nullptr)
{
SharedPtr<Node> nextNode = curNode->NextPreOrder(doc);
if (curNode->PreviousPreOrder(doc) != nullptr && nextNode != nullptr)
{
ASPOSE_ASSERT_EQ(curNode, nextNode->PreviousPreOrder(doc));
}
if (curNode->get_NodeType() == NodeType::Shape && (System::DynamicCast<Shape>(curNode))->get_HasImage())
{
curNode->Remove();
}
curNode = nextNode;
}
ASSERT_EQ(0,
doc->GetChildNodes(NodeType::Shape, true)->LINQ_OfType<SharedPtr<Shape>>()->LINQ_Count([](SharedPtr<Shape> s) { return s->get_HasImage(); }));

◆ Remove()

void Aspose::Words::Node::Remove ( )

Removes itself from the parent.

Examples

Shows how to delete all shapes with images from a document.

auto doc = MakeObject<Document>(MyDir + u"Images.docx");
SharedPtr<NodeCollection> shapes = doc->GetChildNodes(NodeType::Shape, true);
ASSERT_EQ(9, shapes->LINQ_OfType<SharedPtr<Shape>>()->LINQ_Count([](SharedPtr<Shape> s) { return s->get_HasImage(); }));
for (const auto& shape : System::IterateOver(shapes->LINQ_OfType<SharedPtr<Shape>>()))
{
if (shape->get_HasImage())
{
shape->Remove();
}
}
ASSERT_EQ(0, shapes->LINQ_OfType<SharedPtr<Shape>>()->LINQ_Count([](SharedPtr<Shape> s) { return s->get_HasImage(); }));

Shows how to remove all child nodes of a specific type from a composite node.

auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
ASSERT_EQ(2, doc->GetChildNodes(NodeType::Table, true)->get_Count());
SharedPtr<Node> curNode = doc->get_FirstSection()->get_Body()->get_FirstChild();
while (curNode != nullptr)
{
// Save the next sibling node as a variable in case we want to move to it after deleting this node.
SharedPtr<Node> nextNode = curNode->get_NextSibling();
// A section body can contain Paragraph and Table nodes.
// If the node is a Table, remove it from the parent.
if (curNode->get_NodeType() == NodeType::Table)
{
curNode->Remove();
}
curNode = nextNode;
}
ASSERT_EQ(0, doc->GetChildNodes(NodeType::Table, true)->get_Count());

◆ set_CustomNodeId()

void Aspose::Words::Node::set_CustomNodeId ( int32_t  value)

◆ ToString() [1/2]

System::String Aspose::Words::Node::ToString ( Aspose::Words::SaveFormat  saveFormat)

Exports the content of the node into a string in the specified format.

Returns
The content of the node in the specified format.
Examples

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD Field");
// GetText will retrieve the visible text as well as field codes and special characters.
ASSERT_EQ(u"\u0013MERGEFIELD Field\u0014«Field»\u0015\u000c", doc->GetText());
// ToString will give us the document's appearance if saved to a passed save format.
ASSERT_EQ(u"«Field»\r\n", doc->ToString(SaveFormat::Text));

Shows how to extract the list labels of all paragraphs that are list items.

auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
doc->UpdateListLabels();
SharedPtr<NodeCollection> paras = doc->GetChildNodes(NodeType::Paragraph, true);
// Find if we have the paragraph list. In our document, our list uses plain Arabic numbers,
// which start at three and ends at six.
for (auto paragraph : System::IterateOver(
paras->LINQ_OfType<SharedPtr<Paragraph>>()->LINQ_Where([](SharedPtr<Paragraph> p) { return p->get_ListFormat()->get_IsListItem(); })))
{
std::cout << "List item paragraph #" << paras->IndexOf(paragraph) << std::endl;
// This is the text we get when getting when we output this node to text format.
// This text output will omit list labels. Trim any paragraph formatting characters.
String paragraphText = paragraph->ToString(SaveFormat::Text).Trim();
std::cout << "\tExported Text: " << paragraphText << std::endl;
SharedPtr<ListLabel> label = paragraph->get_ListLabel();
// This gets the position of the paragraph in the current level of the list. If we have a list with multiple levels,
// this will tell us what position it is on that level.
std::cout << "\tNumerical Id: " << label->get_LabelValue() << std::endl;
// Combine them together to include the list label with the text in the output.
std::cout << "\tList label combined with text: " << label->get_LabelString() << " " << paragraphText << std::endl;
}

Exports the content of a node to String in HTML format.

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
SharedPtr<Node> node = doc->get_LastSection()->get_Body()->get_LastParagraph();
// When we call the ToString method using the html SaveFormat overload,
// it converts the node's contents to their raw html representation.
ASSERT_EQ(String(u"<p style=\"margin-top:0pt; margin-bottom:8pt; line-height:108%; font-size:12pt\">") +
u"<span style=\"font-family:'Times New Roman'\">Hello World!</span>" + u"</p>",
node->ToString(SaveFormat::Html));
// We can also modify the result of this conversion using a SaveOptions object.
auto saveOptions = MakeObject<HtmlSaveOptions>();
saveOptions->set_ExportRelativeFontSize(true);
ASSERT_EQ(String(u"<p style=\"margin-top:0pt; margin-bottom:8pt; line-height:108%\">") +
u"<span style=\"font-family:'Times New Roman'\">Hello World!</span>" + u"</p>",
node->ToString(saveOptions));

◆ ToString() [2/2]

System::String Aspose::Words::Node::ToString ( const System::SharedPtr< Aspose::Words::Saving::SaveOptions > &  saveOptions)

Exports the content of the node into a string using the specified save options.

Parameters
saveOptionsSpecifies the options that control how the node is saved.
Returns
The content of the node in the specified format.
Examples

Exports the content of a node to String in HTML format.

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
SharedPtr<Node> node = doc->get_LastSection()->get_Body()->get_LastParagraph();
// When we call the ToString method using the html SaveFormat overload,
// it converts the node's contents to their raw html representation.
ASSERT_EQ(String(u"<p style=\"margin-top:0pt; margin-bottom:8pt; line-height:108%; font-size:12pt\">") +
u"<span style=\"font-family:'Times New Roman'\">Hello World!</span>" + u"</p>",
node->ToString(SaveFormat::Html));
// We can also modify the result of this conversion using a SaveOptions object.
auto saveOptions = MakeObject<HtmlSaveOptions>();
saveOptions->set_ExportRelativeFontSize(true);
ASSERT_EQ(String(u"<p style=\"margin-top:0pt; margin-bottom:8pt; line-height:108%\">") +
u"<span style=\"font-family:'Times New Roman'\">Hello World!</span>" + u"</p>",
node->ToString(saveOptions));

◆ Type()

static const System::TypeInfo& Aspose::Words::Node::Type ( )
static