I'm generating some xml in code (as a string) and I want to set the string then as the sub elements of an existing node (using xmlNodeSetContent).
The problem is that either the xmlNodeSetContent function or the XML saving function I'm using (xmlSaveFormatFileEnc) is escaping the '<' and '>' characters as '& lt;' and '& gt;'
How do I switch the escaping off in this instance? Or, can I format the string to disable the escaping?
Possible answer:
One solution I have tried is to add the relevant XML header and main element around the text string and then load the string as if it is a second XML document. I can then take the new document children and/or content and add it to my existing node. This works, but I'm hoping there is a simpler way.
Clarification:
One part of my program is generating XML and only returning it as a string. I would like to take this string and inject it into an existing document. If I use xmlNodeSetContent it sort of works, except that some of of the XML syntax is escaped, which I don't want.
I'm now using the following code to inject XML text (possibly containing multiple elements) into an existing node (thanks to Nazar and nwellnhof for the one answer and referring me to How to add a xml node constructed from string in libxml2):
std::string xml = "<a>" + str + "</a>";
xmlNodePtr pNewNode = nullptr;
xmlParseInNodeContext(pParentNode, xml.c_str(), (int)xml.length(), 0, &pNewNode);
if (pNewNode != nullptr)
{
// add new xml node children to parent
xmlNode *pChild = pNewNode->children;
while (pChild != nullptr)
{
xmlAddChild(pParentNode, xmlCopyNode(pChild, 1));
pChild = pChild->next;
}
xmlFreeNode(pNewNode);
}
It takes the string (str) adds a surrounding element (< a >...< a/ >), parses the string using xmlParseInNodeContext and then adds the children of the new node to the parent. It is important to add the children of the new node and not the new node to avoid having < a >...< a/ > in the final XML.
libxml2 has a function to create a document fragment. This is exposed in some languages as createDocumentFragment() method on the document object.
Originally it should be the function xmlNewDocFragment