c - libxml2 所有 xml 转 char

标签 c xml string libxml2

有没有一种简单的方法可以从 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/

相关文章:

XML 搜索——速度快,节点内的文本或文本作为属性值

C - 字符串连接

c - 编译器/解释器中的符号前瞻

c - 在 C 中使用 typedef 的函数指针

c - 如何在字符串数组中查找重复的字符串

java - 将 XML 数据传递到文件中

c - 为什么会出现段错误?

java - 无法处理 DOMSource : check that saxon9-dom. jar 在类路径上

java - 从 Java 中的单词打印元音

java - 两个字符之间的字符串的正则表达式