美文网首页
c语言libxml2解析xml

c语言libxml2解析xml

作者: 一路向后 | 来源:发表于2021-07-22 22:46 被阅读0次

1.xml样本文件test.xml

<?xml version="1.0"?>
<root>
    <newNode1>newNode1 content</newNode1>
    <newNode2>newNode2 content</newNode2>
    <newNode3>newNode3 content</newNode3>
    <node2 attribute="yes">NODE CONTENT</node2>
    <son>
        <grandson>This is a grandson node</grandson>
    </son>
</root>

2.源码实现

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

int main(int argc, char **argv)
{
    xmlDocPtr doc;
    xmlNodePtr curNode;
    xmlChar *szKey;
    char *szDocName;

    if(argc <= 1)
    {
        printf("Usage: %s docname\n", argv[0]);

        return 0;
    }

    szDocName = argv[1];

    /*解析文件*/
    doc = xmlReadFile(szDocName, "UTF-8", XML_PARSE_RECOVER);

    if(doc == NULL)
    {
        fprintf(stderr, "Document not parsed successful.\n");

        return -1;
    }

    /*确定文档根元素*/
    curNode = xmlDocGetRootElement(doc);

    if(curNode == NULL)
    {
        fprintf(stderr, "empty document\n");
        xmlFreeDoc(doc);
        return -1;
    }

    /*确认文档类型*/
    if(xmlStrcmp(curNode->name, BAD_CAST"root"))
    {
        fprintf(stderr, "document of the wrong type, root node != root\n");
        xmlFreeDoc(doc);
        return -1;
    }

    /*找到子节点*/
    curNode = curNode->xmlChildrenNode;
    xmlNodePtr propNodePtr = curNode;

    while(curNode != NULL)
    {
        /*取出节点中的内容*/
        if((!xmlStrcmp(curNode->name, (const xmlChar *)"newNode1")))
        {
            szKey = xmlNodeGetContent(curNode);
            printf("newNode1: %s\n", szKey);
            xmlFree(szKey);
        }

        /*查找带有属性attribute的节点*/
        if(xmlHasProp(curNode, BAD_CAST"attribute"))
        {
            propNodePtr = curNode;
        }

        curNode = curNode->next;
    }

    /*查找属性*/
    xmlAttrPtr attrPtr = propNodePtr->properties;

    while(attrPtr != NULL)
    {
        if(!xmlStrcmp(attrPtr->name, BAD_CAST"attribute"))
        {
            xmlChar *szAttr = xmlGetProp(propNodePtr, BAD_CAST"attribute");
            printf("get attribute = %s\n", szAttr);
            xmlFree(szAttr);
        }

        attrPtr = attrPtr->next;
    }

    xmlFreeDoc(doc);

    return 0;
}

3.编译源码

$ gcc -o ParseXmlFile ParseXmlFile.c -I/usr/local/include/libxml2 -L/usr/local/lib -lxml2

4.运行及其结果

$ ./ParseXmlFile test.xml 
newNode1: newNode1 content
get attribute = yes

相关文章

网友评论

      本文标题:c语言libxml2解析xml

      本文链接:https://www.haomeiwen.com/subject/ipaymltx.html