我第一次使用 xml,在将 xml 文件的内容存储在数组中时遇到了一些问题。我正在使用 libxml2 来解析 xml 文件,并且我能够获取数据并能够打印它。代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <wchar.h>
wchar_t buffer[7][50]={"\0"};
static void parseDoc(const char *docname)
{
xmlDocPtr doc;
xmlNodePtr cur;
xmlChar *key;
int i=0;
doc = xmlParseFile(docname);
if (doc == NULL ) {
fprintf(stderr,"Document not parsed successfully. \n");
return;
}
cur = xmlDocGetRootElement(doc);
if (cur == NULL)
{
fprintf(stderr,"empty document\n");
xmlFreeDoc(doc);
return;
}
cur = cur->xmlChildrenNode;
while (cur != NULL)
{
key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
wmemcpy(buffer[i],(wchar_t*)(key),size(key)); /*segmentation fault at this stage*/
printf("Content : %s\n", key);
xmlFree(key);
i++;
cur = cur->next;
}
xmlFreeDoc(doc);
return;
}
int main(void)
{
const char *docname="/home/workspace/TestProject/Text.xml;
parseDoc (docname);
return (1);
}
下面提供了示例 xml 文件
<?xml version="1.0"?>
<story>
<author>John Fleck</author>
<datewritten>June 2, 2002</datewritten>
<keyword>example keyword</keyword>
<headline>This is the headline</headline>
<para>This is the body text.</para>
</story>
打印在屏幕上时文件内容的输出如下
Content : null
Content : John Fleck
Content : null
Content : June 2, 2002
Content : null
Content : example keyword
Content : null
Content : This is the headline
Content : null
Content : This is the body text.
我觉得文件的内容在少数地方为空导致了复制问题,从而产生了分段错误。请让我知道如何解决这个问题,是否有更好的方法来完成这件事。我使用 MSXML 解析器完成了类似的 xml 文件读取,这是我第一次使用 Linux API。
编辑复制部分执行如下,但 wchart 数组的内容是乱码。进一步的帮助将不胜感激。
while (cur != NULL) {
key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
if(key!=NULL)
{
wmemcpy(DiscRead[i],(const wchar_t *)key,sizeof(key));
i++;
}
printf("keyword: %s\n", key);
xmlFree(key);
cur = cur->next;
}