用C语言打印XML格式的节点

时间:2015-11-14 03:59:08

标签: c xml

我尝试打印示例文件中的节点。但我继续在每个节点后打印(文本)。请帮忙..

查看标记为相关信息的图片:photo photo

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


int main(int argc, char **argv){

  xmlDoc         *document;
  xmlNode        *root, *first_child, *node, *sibling, *grand_child, *node2, *node3;
  char           *filename;


filename = argv[1];

document = xmlReadFile("sample.xml", NULL, 0);
root     = xmlDocGetRootElement(document);

fprintf(stdout, "Root is <%s>\n", root->name);


first_child = root->children;
for (node = first_child; node!=NULL; node = node->next){ 
     fprintf(stdout, "\t Child is <%s>\n", node->name);
     grand_child=node->children;

        for (node2= grand_child; node2!=NULL; node2 = node2->next){
            fprintf(stdout, "\tGrand_Child is <%s>\n",node2->name);
            sibling=node2->children;

            for (node3= sibling; node3!=NULL; node3 = node3->next){
               fprintf(stdout, "\t Sibling is <%s>\n",node3->name);
            }

        }
}
return 0;}

1 个答案:

答案 0 :(得分:0)

如果您不想要文本节点,则只打印类型为XML_ELEMENT_NODE的节点。也就是说,打印代码应首先检查type字段:

if (node->type == XML_ELEMENT_NODE) {
    fprintf(stdout, "\t Child is <%s>\n", node->name);
}