gpt4 book ai didi

c - 使用 libxml 的 XML 解析器

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:26:37 24 4
gpt4 key购买 nike

我刚开始使用 libxml 来解析 xml。我只需要知道根节点“beatles”是否存在,然后获取子节点“lastname”。我的代码在下面

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

void parseStory ( xmlDocPtr doc, xmlNodePtr cur )
{

xmlChar *key;
cur = cur -> xmlChildrenNode;
printf ( "Here\n" );
while ( cur != NULL )
{
if ( ( !xmlStrcmp ( cur -> name, ( const xmlChar * ) "lastname" ) ) )
{
key = xmlNodeListGetString ( doc, cur -> xmlChildrenNode,1);
printf ( "keyword: %s\n", key );
xmlFree ( key );
}
cur = cur -> next;
}
return ;
}

static void parseDoc ( char *docname )
{
xmlDocPtr doc;
xmlNodePtr cur;
doc = xmlParseFile ( docname );

if ( doc == NULL )
{
fprintf ( stderr, "Document not parsed successfully. \n" );
return;
}
printf ( "Parsing Successful\n" );
cur = xmlDocGetRootElement ( doc );

if ( cur == NULL )
{
fprintf ( stderr, "empty document \n" );
xmlFreeDoc ( doc );
return;
}

printf ( "Got the root Node\n" );
if ( xmlStrcmp ( cur->name, ( const xmlChar * ) "beatles" ) )
{
fprintf ( stderr, "Document of the wrong type root node != ");
xmlFreeDoc(doc);
return;

}
printf ( "Got the root \n" );
cur = cur -> xmlChildrenNode;
while ( cur != NULL )
{
if ( !(xmlStrcmp ( cur->name, ( const xmlChar * ) "name" ) ) )
{
parseStory ( doc, cur );
}
cur = cur -> next;
}
xmlFreeDoc ( doc );
return;
}

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

if ( argc <= 1 )
{
printf ( "Usage: %s docname\n", argv[0] );
return ( 0 );
}
docname = argv [1];
parseDoc ( docname );

return ( 1 );
}

xml文件是

<?xml version="1.0"?>
<beatles>
<beatle link="http://www.paulmccartney.com">
<name>
<firstname>Paul</firstname>
<lastname>McCartney</lastname>
</name>
</beatle>

我可以获取根节点“beatles”,但找不到“name”和“lastname”。请在这件事上给予我帮助。

如果还有其他的libxml函数可以使用,请告诉我。谢谢。

最佳答案

您需要在 while 循环中做一些小改动。

printf ( "Got the root \n" );
cur = cur -> xmlChildrenNode;
while ( cur != NULL )
{
if (cur->type == XML_ELEMENT_NODE) {

if ( !(xmlStrcmp ( cur->name, ( const xmlChar * ) "name" ) ) )
{
parseStory ( doc, cur );
}
cur = cur -> xmlChildrenNode;
continue;
}
cur = cur -> next;
}

关于c - 使用 libxml 的 XML 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11381460/

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