最近做嵌入式項目,需要生成XML狀態(tài)報文,C++的XML的解析器就不能用了。然后使用xmllib2,功能挺多,也很穩(wěn)定,就是太大了,不利于移植到ARM,而且有很多的功能用不上,編譯部署麻煩。一日,看了一本書上好像這么說: 一個工具解決的問題比它引入的問題還多,就去掉它,重新從零開始。感覺說得的有道理,我還不如自己寫一個。Forge....
花了一下午,共200行C代碼完成了一個XML文檔生成器,測試了一下效率相當(dāng)高,也很穩(wěn)定,感覺好極了。那位大哥如果能做的更精巧,不妨提攜一下小弟,不吝指教。
工程名稱:MiniXML
工程下載:
http://www.shnenglu.com/Files/dyj057/minixml.zip
在XP+VS2003中編譯通過,你也可以在Linux,Unix上使用。
使用例子:
xmlNodePtr?child;
????????xmlNodePtr?nameNode?;
????????xmlDocPtr?doc?
=
?xmlNewDoc();
????????doc
->
root?
=
?xmlNewNode(
"
employees
"
);
????????child?
=
?xmlAddChild(doc
->
root,?xmlNewNode(
"
employee
"
));
????????xmlAddProp(child,
"
age
"
,
"
28
"
);
????????xmlAddProp(child,
"
sexy
"
,
"
male
"
);
????????nameNode?
=
?xmlAddChild(child,?xmlNewNode(
"
name
"
));
????????xmlAddText(nameNode,?xmlNewText(
"
Nicholas?C.?Zakas
"
));
????????child?
=
?xmlAddChild(doc
->
root,?xmlNewNode(
"
employee
"
));
????????xmlAddProp(child,
"
age
"
,
"
22
"
);
????????xmlAddProp(child,
"
sexy
"
,
"
male
"
);
????????nameNode?
=
?xmlAddChild(child,?xmlNewNode(
"
name
"
));
????????xmlAddText(nameNode,?xmlNewText(
"
Jim?Smith
"
));
????????printfXmlDoc(stdout,doc);
????????xmlFreeDoc(doc);
生成XML文檔如下:
<?xml version="1.0" encoding="utf-8"?>
<employees>
?<employee age="28" sexy="male">
??<name>Nicholas C. Zakas</name>
?</employee>
?<employee age="22" sexy="male">
??<name>Jim Smith</name>
?</employee>
</employees>
Functions
|
xmlDocPtr
?
|
xmlNewDoc
()
|
? |
xmlDoc
struct pointer
|
void?
|
xmlFreeDoc
(
xmlDocPtr
doc)
|
? |
free XML document struct
|
void?
|
xmlFreeNode
(
xmlNodePtr
node)
|
? |
free XML document struct
|
void?
|
xmlAddText
(
xmlNodePtr
node,
xmlTextNodePtr
text)
|
? |
add a text node to a element
|
xmlNodePtr
?
|
xmlNewNode
(const char *name)
|
? |
create a new element node
|
xmlTextNodePtr
?
|
xmlNewText
(const char *text)
|
? |
create a new text node
|
xmlNodePtr
?
|
xmlAddChild
(
xmlNodePtr
father,
xmlNodePtr
child)
|
? |
add child node to the father node
|
void?
|
xmlAddProp
(
xmlNodePtr
node, const char *propName, const char *propValue)
|
? |
add property to a node
|
void?
|
printfXmlDoc
(FILE *f,
xmlDocPtr
doc)
|
? |
print document's XML to a file |
?
|
|
posted on 2007-01-29 11:31
天下無雙 閱讀(5297)
評論(11) 編輯 收藏 引用 所屬分類:
C/C++