我使用Libxml2来编码xml文件中的数据.我的数据包含“<”等标签和“>”.当它被转换成xml时,这些标签也被转换成“& lt”和“& gt”.有没有办法解决这个问题.我想在解码那个xml文件时将这些标签用作xml节点,因此CDATA不是解决此问题的方法.请为此提供任何解决方案.谢谢.
示例代码:
xmlNewChild(node,NULL,(xmlChar *)"ADDRESS",(xmlChar *)"<street>Park Street</street><city>kolkata</city>"); and output of above code is: <person> <ADDRESS><street>Park Street</street><city>Kolkata</city></ADDRESS>
如果你想要一个字符串被视为xml,那么你应该解析它并使用
xmlReadMemory从它获取xmlDoc.它可以用于更大的字符串,但通常使用单步指令构建文档,如Joachim的答案.在这里,我提出了xmlAddChildFromString函数来以字符串方式执行这些操作.
原文链接:https://www.f2er.com/xml/292122.html#include <stdio.h> #include <string.h> #include <libxml/parser.h> #include <libxml/tree.h> /// Returns 0 on failure,1 otherwise int xmlAddChildFromString(xmlNodePtr parent,xmlChar *newNodeStr) { int rv = 0; xmlChar *newNodeStrWrapped = calloc(strlen(newNodeStr) + 10,1); if (!newNodeStrWrapped) return 0; strcat(newNodeStrWrapped,"<a>"); strcat(newNodeStrWrapped,newNodeStr); strcat(newNodeStrWrapped,"</a>"); xmlDocPtr newDoc = xmlReadMemory( newNodeStrWrapped,strlen(newNodeStrWrapped),0); free(newNodeStrWrapped); if (!newDoc) return 0; xmlNodePtr newNode = xmlDocCopyNode( xmlDocGetRootElement(newDoc),parent->doc,1); xmlFreeDoc(newDoc); if (!newNode) return 0; xmlNodePtr addedNode = xmlAddChildList(parent,newNode->children); if (!addedNode) { xmlFreeNode(newNode); return 0; } newNode->children = NULL; // Thanks to milaniez newNode->last = NULL; // for fixing xmlFreeNode(newNode); // the memory leak. return 1; } int main(int argc,char **argv) { xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0"); xmlNodePtr root = xmlNewNode(NULL,BAD_CAST "root"); xmlDocSetRootElement(doc,root); xmlAddChildFromString(root,"<street>Park Street</street><city>kolkata</city>"); xmlDocDump(stdout,doc); xmlFreeDoc(doc); return(0); }