- 论坛徽章:
- 0
|
我接触XMLLIB时间不长,有一问题向各位求教,这是一个从网上下载的例子。
源码如下addKeyword.c:
#include <stdio.h>;
#include <string.h>;
#include <stdlib.h>;
#include <libxml/xmlmemory.h>;
#include <libxml/parser.h>;
void
parseStory (xmlDocPtr doc, xmlNodePtr cur, char *keyword) {
xmlNewTextChild (cur, NULL, "keyword", keyword);
return;
}
xmlDocPtr
parseDoc(char *docname, char *keyword) {
xmlDocPtr doc;
xmlNodePtr cur;
doc = xmlParseFile(docname);
if (doc == NULL ) {
fprintf(stderr,"Document not parsed successfully. \n" ;
return (NULL);
}
cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
fprintf(stderr,"empty document\n" ;
xmlFreeDoc(doc);
return (NULL);
}
if (xmlStrcmp(cur->;name, (const xmlChar *) "story" ) {
fprintf(stderr,"document of the wrong type, root node != story" ;
xmlFreeDoc(doc);
return (NULL);
}
cur = cur->;xmlChildrenNode;
while (cur != NULL) {
if ((!xmlStrcmp(cur->;name, (const xmlChar *)"storyinfo" )){
parseStory (doc, cur, keyword);
}
cur = cur->;next;
}
return(doc);
}
int
main(int argc, char **argv) {
char *docname;
char *keyword;
xmlDocPtr doc;
if (argc <= 2) {
printf("Usage: %s docname, keyword\n", argv[0]);
return(0);
}
docname = argv[1];
keyword = argv[2];
doc = parseDoc (docname, keyword);
if (doc != NULL) {
xmlSaveFormatFile (docname, doc, 0);
xmlFreeDoc(doc);
}
return (1);
}
其所使用的英文XML样例如下example.xml(UTF-8编码):
<?xml version="1.0"?>;
<story>;
<storyinfo>;
<author>;John Fleck</author>;
<datewritten>;June 2, 2002</datewritten>;
<body>;
<headline>;This is the headline</headline>;
<para>;This is the body text.</para>;
</body>;
</story>;
其所使用的含中文XML样例如下example_c.xml(UTF-8编码):
<?xml version="1.0"?>;
<story>;
<storyinfo>;
<author>;发射点反抗六十九赶快John Fleck</author>;
<datewritten>;June 2, 2002士大夫士大夫</datewritten>;
<keyword>;example 士大夫士大夫士大夫感keyword</keyword>;
</storyinfo>;
<body>;
<headline>;豆腐干大概This is the headline</headline>;
<para>;This is the 大幅度法ody text.</para>;
</body>;
</story>;
用addKeyword运行:
addKeyword example.xml test_add_keyword
addKeyword example_c.xml test_add_keyword
结果英文xml文件运行后正常,而中文xml变成:
<?xml version="1.0"?>;
<story>;
<storyinfo>;
<author>;&#x53D1;&#x5C04;&#x70B9;&#x53CD;&#x6297;&#x516D;&#x5341;&#x4E5D;&#x8D76;&#x5FEB;
John Fleck</author>;
<datewritten>;June 2, 2002&#x58EB;&#x5927;&#x592B;&#x58EB;&#x5927;&#x592B;</datewritten>;
<keyword>;example
&#x58EB;&#x5927;&#x592B;&#x58EB;&#x5927;&#x592B;&#x58EB;&#x5927;&#x592B;&#x611F;keyword</
keyword>;
<keyword>;test_add_keyword</keyword>;</storyinfo>;
<body>;
<headline>;&#x8C46;&#x8150;&#x5E72;&#x5927;&#x6982;This is the headline</headline>;
<para>;This is the &#x5927;&#x5E45;&#x5EA6;&#x6CD5;ody text.</para>;
</body>;
</story>;
不知诸位有何高见,望不吝赐教。本人不胜感激! |
|