Thursday, August 20, 2009

MSXML append xml fragment as child

A C/C++ method used to append XML text to an MSXML node/element as child. The appendChild function can append only node/element objects. Sometimes it's easier or more convenient to create the XML with text concatenation than by building it using MSXML. And the code:

void appendXmlText(MSXML2::IXMLDOMElementPtr elem, _bstr_t xmlText)
{
//only one root elem is allowed!
_bstr_t xmlFragment = "<fragment>" + xmlText + "</fragment>";

MSXML2::IXMLDOMDocument2Ptr _doc;
TESTHR(_doc.CreateInstance(__uuidof(MSXML2::DOMDocument40)));
_doc->validateOnParse = false;
_doc->resolveExternals = false;

_doc->loadXML(xmlFragment);
MSXML2::IXMLDOMElementPtr root = _doc->documentElement;
MSXML2::IXMLDOMNodeListPtr childs = root->childNodes;
long childCount = root->childNodes->length;
for (long i = 0; i < childCount; ++i)
{
MSXML2::IXMLDOMNodePtr childNode = root->childNodes->item[i];
elem->appendChild(childNode->cloneNode(VBOOL_TRUE));
//VBOOL_TRUE is -1
}
}

No comments: