0
我對使用libxml2的xmlNewChild函數有一個非常奇怪的錯誤。我試圖儘可能縮短帖子,所以我刪除了一些微不足道的邏輯。爲每個要寫入的變量定義一個布爾變量,當設置變量值時,布爾值設置爲TRUE,指示標籤是否存在,如果是,則寫入,否則將被跳過xmlNewChild並不總是寫入元素的值
我已經定義了一個結構如下:
tyedef struct _xml_parse_t
{
const char *name;
void *variable;
int type;
_xml_parse_t *childs;
} xml_parse_t;
另一個函數解析此結構並將其寫入char *。功能定義如下:
int generate_xml(xml_parse_t *p, char *out, const char*root)
{
xmlChar *s = NULL;
int size = 0;
xmlDocPtr doc = NULL;
xmlNodePtr root_node = NULL;
doc = xmlNewDoc(NULL);
if(NULL == doc)
return -1;
root_node = xmlNewNode(NULL, BAD_CAST root);
if(NULL == root_node)
return -1;
else
xmlDocSetRootElement(doc, root_node);
if(-1 == writeXmlToDoc(p, doc, root_node))
return -1;
xmlDocDumpFormatMemoryEnc(doc, &s, &size, "UTF-8", 1);
if(NULL == s)
return -1;
if(SUCCEED == ret)
strcpy(out, (char *)s);
if(NULL != s)
xmlFree(s);
xmlFreeDoc(doc);
xmlCleanupParser();
xmlMemoryDump();
return 0;
}
的writeXmlToDoc定義如下
int writeXmlToDoc(xml_parse_t *parse, xmlDocPtr doc,
xmlNodePtr root_node)
{
xml_parse_t *p = parse;
xmlNodePtr node;
while(NULL != p->name)
{
if(NODE_TYPE_PARENT == p->type && NULL != p->childs)
{
node = xmlNewChild(root_node, NULL, BAD_CAST p->name, NULL);
if(-1 == writeXmlToDoc(p->childs, doc, node))
return -1;
}
else
{
printf("Current value being written [%s]", (char *)cvtToXmlChar(p->variable, p->type));
node = xmlNewChild(root_node, NULL, BAD_CAST p->name,
BAD_CAST cvtToXmlChar(p->variable, p->type));
}
p++;
}
return 0;
}
要保持此交儘可能短,則cvtToXmlChar檢查變量的類型並將它轉換到XMLCHAR和xmlNewChild之前的printf顯示變量的正確值。
xml_parse_t child_parse[] = {
/* Name var Type Childs*/
{"ChildInt", &test_int1, NODE_TYPE_INT, NULL },
{"ChildLong", &test_long1, NODE_TYPE_LONG, NULL },
{"ChildChar", test_char1, NODE_TYPE_STRING, NULL },
{"ChildShort", &test_short1, NODE_TYPE_SHORT, NULL },
{"ChildDouble", &test_double1,NODE_TYPE_DOUBLE, NULL },
{ NULL }
};
xml_parse_t parent_parse[] = {
/* Name var Type Childs*/
{"ParentInt", &test_int, NODE_TYPE_INT, NULL },
{"ParentLong", &test_long, NODE_TYPE_LONG, NULL },
{"ParentChar", test_char, NODE_TYPE_STRING, NULL },
{"ParentShort", &test_short, NODE_TYPE_SHORT, NULL },
{"ParentDouble", &test_double, NODE_TYPE_DOUBLE, NULL },
{"ParentParent", NULL, NODE_TYPE_PARENT, child_parse },
{ NULL }
};
和設置的變量如下:
test_int = 1;
test_int1 = 2;
test_long = 1;
test_long1 = 2;
sprintf(test_char, "TestParentCharTag");
sprintf(test_char1, "TestChildCharTag");
test_short = 1;
test_short1 = 2;
test_double = 1;
test_double1 = 2;
的問題是,在輸出串具有2個缺失值。以下是運行測試
<ROOTELEMENT>
<ParentInt>1</ParentInt>
<ParentLong></ParentLong>
<ParentChar>TestParentCharTag</ParentChar>
<ParentShort>1</ParentShort>
<ParentDouble>1.000000</ParentDouble>
<ParentParent>
<ChildInt></ChildInt>
<ChildLong>2</ChildLong>
<ChildChar>TestChildCharTag</ChildChar>
<ChildShort>2</ChildShort>
<ChildDouble>2.000000</ChildDouble>
</ParentParent>
</ROOTELEMENT>