glib 学习笔记,解析xml文件

本文介绍了一种使用glib库基于事件类型解析XML文件的方法,并通过具体代码示例展示了如何实现这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明出处,或联系
fanyuanmail@126.com
xml的用处越来越广泛了,解析xml得库也非常多,总的来说分为两种,一种是把xml当作一个“树”来进行解析,一种是基于事件类型的

glib就是使用事件类型解析xml。


#include stdio.h>
gchar *current_animal_noise = NULL;
static void start(GMarkupParseContext *context,
        const gchar *element_name,
        const gchar **attribute_names,
        const gchar **attribute_values,
        gpointer user_data,
        GError **error)
{
        const gchar **name_cursor = attribute_names;
        const gchar **value_cursor = attribute_values;
        while (*name_cursor) {
                if (strcmp (*name_cursor, "noise") == 0)
                current_animal_noise = g_strdup (*value_cursor);
                name_cursor++;
                value_cursor++;
        }
}
static void end(GMarkupParseContext *context,
        const gchar *element_name,
        gpointer user_data,
        GError **error)
{
        if (current_animal_noise)
        {
                g_free (current_animal_noise);
                current_animal_noise = NULL;
        }
}
static void text(GMarkupParseContext *context,
        const gchar *text,
        gsize text_len,
        gpointer user_data,
        GError **error)
{
        if (current_animal_noise)
                printf("I am a %*s and I go %s. Can you do it?/n",
                    text_len, text, current_animal_noise);
        printf("test text/n");
}
GMarkupParser parser = {
        .start_element = start,
        .end_element = end,
        .text = text,
        .passthrough = NULL,
        .error = NULL
};
int main()
{
        char *buf;
        gsize length;
        GMarkupParseContext *context;
        g_file_get_contents("test.xml", &buf, &length,NULL);
        g_printf("%s/n",buf);
        context = g_markup_parse_context_new(&parser, 0, NULL, NULL);
        if (g_markup_parse_context_parse(context, buf, length, NULL) == FALSE)
        {
                printf("Couldn't load xml/n");
                g_markup_parse_context_free(context);
        return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值