gpt4 book ai didi

c - 如何使用c或javascript或lua查找XML文件的父节点?

转载 作者:行者123 更新时间:2023-11-30 14:24:14 26 4
gpt4 key购买 nike

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

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

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

有人可以帮忙吗?

最佳答案

尝试以下代码(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!

关于c - 如何使用c或javascript或lua查找XML文件的父节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12077871/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com