0

我有一个如下所示的 xml 文件。

<?xml version="1.0"?>
-<dsl1> <host2> </host2> -<switch3> <host4> </host4> </switch3> <host5> </host5> -<switch6> <host7> </host7> <host8> </host8> </switch6> </dsl1>

我想找到每个元素的父级。例如:host7 父级是 6。

有人可以帮忙吗?

4

1 回答 1

2

试试这个代码(node_parent_dump.c):

/* Compile like this :
 * gcc -Wall node_parent_dump.c -o node_parent_dump `xml2-config --cflags` `xml2-config --libs` 
 */
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int found = 0;

int walk_tree(xmlNode *node, xmlDocPtr doc, char *pattern)
{
        xmlNode *cur_node = NULL;

        for (cur_node = node; cur_node; cur_node = cur_node->next)
        {
                if ((!xmlStrcmp(cur_node->name, (const xmlChar *)pattern)))
                {
                        found++;
                        fprintf(stdout, "\n----> WE GOT IT\n\n");
                        fprintf(stdout, "The father's name is : %s\n", cur_node->parent->name);
                        fprintf(stdout, "\n<----\n");
                }
                walk_tree(cur_node->children, doc, pattern);
        }

        return found;
}

int main(int argc, char **argv)
{
        xmlDocPtr xml_doc;
        xmlNodePtr xml_root;
        int ret;
        char xml_file[] = "my_file.xml";

        if (argc != 2)
        {
                fprintf(stderr, "Usage : ./node_parent_dump node\n");

                exit(EXIT_FAILURE);
        }

        /* Read the XML file */
        if ((xml_doc = xmlParseFile (xml_file)) == NULL)
        {
                fprintf (stderr, "xmlParseFile failed\n");

                exit(EXIT_FAILURE);
        }

        /* Get the root node */
        if ((xml_root = xmlDocGetRootElement (xml_doc)) == NULL)
        {
                fprintf (stderr, "No root found\n");
                xmlFreeDoc (xml_doc);

                exit (EXIT_FAILURE);
        }

        /* Traverse all the tree to find the given node (pattern) */
        ret = walk_tree(xml_root, xml_doc, argv[1]);
        if (!ret)
                fprintf(stdout, "No luck, this node does not exit!\n");

        return 0;
}

在linux下可以这样编译:

gcc -Wall node_parent_dump.c -o node_parent_dump `xml2-config --cflags` `xml2-config --libs`

并像这样测试它:

toc@UnixServer:~$ ./node_parent_dump hello
No luck, this node does not exit!
toc@UnixServer:~$ ./node_parent_dump host7

----> WE GOT IT

The father's name is : switch6

<----
toc@UnixServer:~$ ./node_parent_dump host6
No luck, this node does not exit!
toc@UnixServer:~$ ./node_parent_dump host2

----> WE GOT IT

The father's name is : dsl1

<----
toc@UnixServer:~$ ./node_parent_dump host4

----> WE GOT IT

The father's name is : switch3

<----
toc@UnixServer:~$ ./node_parent_dump host23
No luck, this node does not exit!
于 2012-08-23T02:26:23.857 回答