在Xerces-C中从DOMNode*传递到DOMElement*

And*_*dry 2 c++ xml dom xerces-c

我有一个操纵xml的c ++应用程序.好吧,在我的应用程序的某个点上,我得到一个DOMNode*然后我把它作为一个孩子附加到一个元素.

那么问题是我想向该节点添加参数......它是一个节点所以它不是一个元素......只有元素有参数......

这是我的代码:

xercesc::DOMNode* node = 0;
std::string xml = from_an_obj_of_mine.GetXml(); /* A string with xml inside, the xml is sure an element having something inside */
xercesc::MemBufInputSource xml_buf((const XMLByte*)xml.c_str(), xml.size(), "dummy");
xercesc::XercesDOMParser* parser = new xercesc::XercesDOMParser();
parser->parse(xml_buf); /* parser will contain a DOMDocument well parsed from the string, I get here the node i want to attach */
node = my_pointer_to_a_preexisting_domdocument->GetXmlDocument()->importNode(parser->getDocument()->getDocumentElement(), true); /* I want to attach the node in parser to a node of my_pointer_to_an_el_of_my_preexisting_domdocument, it is a different tree, so I must import the node to attach it later */
my_pointer_to_an_el_of_my_preexisting_domdocument->appendChild(node);
Run Code Online (Sandbox Code Playgroud)

如您所见,我想从字符串创建节点,我通过解析创建它,然后需要导入节点以创建属于我想要附加新节点的dom树的新的相同节点.我的步骤是:

  • 获取xml字符串以附加到预先存在的dom(存储为某处的domdocument)

  • 创建一个解析器

  • 使用解析器从字符串创建一个dom树

  • 从我预先存在的dom(我想要附加我的新节点),调用导入并克隆节点,以便它可以附加到预先存在的dom.

  • 附上它

问题是导入和导入让我得到一个节点...我想要一个元素来附加...

我使用appendChild来追加元素......当然这个方法需要DOMNode*但给它一个DOMElement*(它继承自DOMNode)是好的...

如何从节点中获取元素?删除wd_parser;

And*_*dry 6

好的我发现了......

只需将节点重新转换为元素即可完成... DOMNode是一个纯虚拟类,它是DOMElement的父级...所以它是正确的,它也是处理事物的方式(从逻辑上讲).

DOMElement* = dynamic_cast<DOMElement*>(node);
Run Code Online (Sandbox Code Playgroud)

:)

  • 嗨,实际上你应该事先用getNodeType()来检查节点的类型.如果它是ELEMENT_NODE,您可以将其强制转换为DOMElement.欲了解更多信息,请访问:http://xerces.apache.org/xerces-c/apiDocs-3/classDOMNode.html (5认同)