在创建的上述代码中,我们发现,所有的节点都是挂在根节点之下的。
其实这句代码: myDocument->LinkEndChild(RootElement);使用了多态方式。类之间的关系如下:
并且LinkEndChild源代码如下:它是父类TiXmlNode中的方法
[html] view plaincopyprint
TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node )
{
assert( node->parent == 0 || node->parent == this );
assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() );
if ( node->Type() == TiXmlNode::DOCUMENT )
{
delete node;
if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN );
return 0;
}
node->parent = this;
node->prev = lastChild;
node->next = 0;
if ( lastChild )
lastChild->next = node;
else
firstChild = node; // it was an empty list.
lastChild = node;
return node;
}
TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node )
{
assert( node->parent == 0 || node->parent == this );
assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() );
if ( node->Type() == TiXmlNode::DOCUMENT )
{
delete node;
if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN );
return 0;
}
node->parent = this;
node->prev = lastChild;
node->next = 0;
if ( lastChild )
lastChild->next = node;
else
firstChild = node; // it was an empty list.
lastChild = node;
return node;
}
这样的话:则只要删除根节点,在程序中myDocument,就相当于把删除了TiXmlNode,相当于调用了TiXmlNode的析构函数。
质疑:网上说这种方式,析构是从叶子到树根。根据TiXmlNode中的析构函数,我们可以得出,是从树根到叶子。
但是我们在Delete myDocument时,应该注意一点:
创建文档时,也就是程序段中的myDocument.若是从堆上创建,则需需要手动释放。如我们上述的片段中,就是在堆上创建的。
TiXmlDocument *myDocument=new TiXmlDocument ();
若是从栈上创建,则不须我们手动释放,而是程序自动调用析构函数。同时我们应该注意,其他的元素必须在堆上创建。因为在TiXmlNode析构函数中,是delete的,但是栈上的东东是不须delete,所以除了根节点之外连接的后代节点是必须从堆上创建。
经过我们解释,明白tinyxml中的原理了吗?只要理解了tinyxml中的类的作用以及类之间的关系,看源码是没问题滴哦。
这篇博客根据创建xml小demo解释了其中存在的疑问。那下篇博客中我们会根据解析xml来答疑解析中存在的问题。