xerces_3_1 approveNode()方法返回NULL

xerces_3_1 adoptNode() method returns NULL

本文关键字:方法 返回 NULL approveNode xerces      更新时间:2023-10-16

我目前在visualstudio2010中使用xerces3.1。

我写了一段(非常简单)代码:

XMLPlatformUtils::Initialize();
DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(L"XML 1.0");
DOMDocument* doc1 = impl->createDocument(L"nsURI", L"abc:root1", 0);
DOMDocument* doc2 = impl->createDocument(0, L"root2", 0);
DOMElement* root1 = doc1->getDocumentElement();
DOMElement* root2 = doc2->getDocumentElement();
DOMElement* el1 = doc1->createElement(L"el1");
root1->appendChild(el1);
DOMNode* tmpNode = doc2->adoptNode(el1);    //tmpNode is null after this line
root2->appendChild(tmpNode);
doc1->release();
doc2->release();
xercesc::XMLPlatformUtils::Terminate();

问题是,不管怎样,adoptNode(...)方法总是会返回一个空指针。我真的不明白这里发生了什么,请帮帮我!

PS:我知道我可以使用importNode(...)方法,从旧文档中删除并释放旧节点,但我希望有一种方法可以解决我的adoptNode(...)问题!

xerces-api为adoptNode(DOMNode* source)声明以下内容:

更改节点的ownerDocument、其子节点以及附加的属性节点(如果有的话)。

经过一些研究,我查看了xerces3.1中adoptNode的实现,可悲的事实是这是不可能的。引用源代码:

if(sourceNode->getOwnerDocument()!=this)
{
    // cannot take ownership of a node created by another document, as it comes from its memory pool
    // and would be delete when the original document is deleted
    return 0;
}

编辑

这个方法有一个变通方法,但它需要一些DOM实现的知识(尤其是在使用UserData时)。您可以使用importNode(...)导入节点,并从旧文档中删除其他节点。

为了不浪费内存,应该释放旧节点!

如果您将用户数据附加到旧节点,则新文档必须具有一些UserDataHandler,它将用户数据从旧节点传递到新节点!

请注意,旧节点上可能的引用现在不会指向新节点。它们必须手动更改(或使用一些UserDataHandler变通方法)