gpt4 book ai didi

c - libxml2 所有 xml 到 char

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:18 24 4
gpt4 key购买 nike

有没有一种简单的方法可以让我从 libxml2 中的 xmlNode 获取 C char *?我想得到这样的东西:"<root id="01"><head>some</head><data>information</data></root>" char *getStringFromXmlNode(xmlNode *node) 中应该有什么?

最佳答案

是这样的。

#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/tree.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void* getValueFromXML(xmlDocPtr doc, xmlChar *xpath )
{
xmlXPathObjectPtr result;
xmlNodeSetPtr nodeset;
xmlChar *keyword;
char *copiedStringPtr;

// Nodes are
// parse the xml document and find those nodes that meet the criteria of the xpath.
result = getnodeset(doc, xpath);

// if it parsed and found anything
if (result)
{
// get the nodes that matched.
nodeset = result->nodesetval;
// go through each Node. There are nodeNr number of nodes.
// nodeset is the seta of all nodes that met the xpath criteria
// For the API look here http://xmlsoft.org/html/libxml-xpath.html
if (nodeset->nodeNr>1)
{
printf("Returned more than one value. Fix the xpath\n");
return NULL;
}

keyword = xmlNodeListGetString(doc, nodeset->nodeTab[0]->xmlChildrenNode, 1);
//printf("keyword: %s\n", keyword);

copiedStringPtr = strdup((const char *)keyword);


xmlFree(keyword);
xmlXPathFreeObject (result);
}

return copiedStringPtr;
}



xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath)
{

xmlXPathContextPtr context; //http://xmlsoft.org/html/libxml-xpath.html#xmlXPathContext
xmlXPathObjectPtr result; // http://xmlsoft.org/html/libxml-xpath.html#xmlXPathObject

// http://xmlsoft.org/html/libxml-xpath.html#xmlXPathNewContext
context = xmlXPathNewContext(doc);
if (context == NULL)
{
printf("Error in xmlXPathNewContext\n");
return NULL;
}

//http://xmlsoft.org/html/libxml-xpath.html#xmlXPathEvalExpression
result = xmlXPathEvalExpression(xpath, context);
xmlXPathFreeContext(context);
if (result == NULL)
{
printf("Error in xmlXPathEvalExpression\n");
return NULL;
}
if (xmlXPathNodeSetIsEmpty(result->nodesetval))
{
xmlXPathFreeObject(result);
printf("No result\n");
return NULL;
}
return result;
}

至少我认为这就是您的要求。希望能帮助到你。

关于c - libxml2 所有 xml 到 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10321274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com