How do I generate XML in a simple format using the C language

  • 2020-04-02 00:54:49
  • OfStack

The code is very simple, posted directly.

    #include <stdio.h>  

    static FILE *out = NULL;  
    static int tabs = 0;  

    void set_out_fp(FILE *fp)  
    {  
        out = fp;  
    }  

    void put(char *str)  
    {  
        fprintf(out, "%s", str);  
    }  

    void put_head(char *head)  
    {  
        put("<?");  
        put(head);  
        put("?>n");  
    }  

    void out_tabs()  
    {  
        int i;  
        for(i=0; i < tabs; i++)  
        {  
            put("t");  
        }  
    }  

    void tag_start(char *tag)  
    {  
        out_tabs();  
        put("<");  
        put(tag);  
        put(">n");  
        tabs = tabs + 1;  
    }  

    void tag_end(char *tag)  
    {  
        tabs = tabs - 1;  
        out_tabs();  
        put("</");  
        put(tag);  
        put(">n");  
    }  

    void tag_value(char *tag, char *value)  
    {  
        out_tabs();  
        put("<");  
        put(tag);  
        put("t");  
        put(""value"="");  
        put(value);  
        put(""");  
        put("t/>n");  
    }  

    void tag_value_num(char *tag, long value)  
    {  
        out_tabs();  
        put("<");  
        put(tag);  
        put("t");  
        put(""value"=");  
        fprintf(out, "%d", value);  
        put("t/>n");  
    }  

    int main()  
    {     
        FILE *fp = fdopen(1, "a");  
        set_out_fp(fp);  

        put_head("xml version='1.0' encoding="GBK"");  
        tag_start(" The delivery information ");  
        tag_start(" hardware ");  

        tag_value_num(" The network card ", 1);  

        tag_end(" hardware ");  
        tag_end(" The delivery information ");  

        fclose(fp);  

        return 0;  
    }  

Related articles: