我正在第一次使用xml,并且在将xml文件的内容存储在数组中时遇到了一些问题。我使用libxml2来解析XML文件,并且能够获取数据并能够打印它。下面的代码中给出:从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;
}
非常感谢你的回答,这就是它。 –
strlcpy没有工作,我用memcpy代替,有没有办法转换成wchart数组。任何帮助都很好。 –
请勿使用'memcpy'来复制字符串。如果您不能使用'strlcpy',请尝试'strncpy',但请注意它有一些注意事项。在Linux上,通常不需要'wchar_t',因为UTF-8是首选的字符编码。 – nwellnhof