在不转义内容的情况下将字符串注入XML节点 [英] Injecting a string into an XML node without content escaping

查看:469
本文介绍了在不转义内容的情况下将字符串注入XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在代码中生成一些xml(作为字符串),然后我想将字符串设置为现有节点的子元素(使用 xmlNodeSetContent ).

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).

问题是我正在使用的 xmlNodeSetContent 函数或XML保存函数( xmlSaveFormatFileEnc )正在转义'<'.和'>'字符作为'& lt;'和'& gt;'

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?

可能的答案: 我尝试过的一种解决方案是在文本字符串周围添加相关的XML标头和主要元素,然后加载该字符串,就好像它是第二个XML文档一样.然后,我可以获取新的文档子级和/或内容,并将其添加到我现有的节点中.这行得通,但我希望有一种更简单的方法.

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.

说明: 我程序的一部分是生成XML,然后仅将其作为字符串返回.我想使用此字符串并将其注入到现有文档中.如果我使用 xmlNodeSetContent ,那么它可以进行一些工作,只是某些XML语法被转义了,这是我不想要的.

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.

推荐答案

我现在正在使用以下代码将XML文本(可能包含多个元素)注入到现有节点中(感谢Nazar和nwellnhof提供了一个答案,将我引至如何添加从libxml2中的字符串构造的xml节点):

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);
}

它使用字符串(str)添加一个周围的元素(< a> ...< a/>),使用xmlParseInNodeContext解析该字符串,然后将新节点的子代添加到父代.重要的是添加新节点的子节点,而不是新节点,以避免<一个> ...< a/>在最终的XML中.

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.

这篇关于在不转义内容的情况下将字符串注入XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆