如果你有兴趣也用C++,你可以尝试rapidxml:
http://rapidxml.sourceforge.net/
http://rapidxml.sourceforge.net/manual.html
在这里,我已经写了解析XML的&打印的内容与深度的示例代码三个层次(和你):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "./rapidxml-1.13/rapidxml.hpp"
#include "./rapidxml-1.13/rapidxml_print.hpp"
#include <iostream>
#include <fstream>
using namespace std;
using namespace rapidxml;
void process_xml(const char* xml){
xml_document<> doc;
char text[strlen(xml)+1];
strcpy(&text[0], xml);
try{
doc.parse<parse_default>(text);
}
catch(rapidxml::parse_error &ex){
cout << "error: rapidxml::parse_error\n";
return;
}
xml_node<> *ptr=NULL;
try{
if (doc.first_node()!=NULL){
for (xml_node<> *node=doc.first_node(); node; node=node->next_sibling()){
cout << "node->name: " << node->name() << endl;
if (strcmp(node->name(), "")!=0){
xml_node<> *content_node = node->first_node();
ptr=content_node;
while ((content_node!=NULL) && (strcmp(content_node->name(), "")!=0)){
cout << "\t>>" << content_node->name() << endl;
for (xml_node<> *node_3rd=content_node->first_node(); node_3rd; node_3rd=node_3rd->next_sibling()){
cout << "name: " << node_3rd->name() << "; ";
cout << "value: " << node_3rd->value() << endl;
}
content_node=content_node->next_sibling();
}
}
}
cout << "\n";
}
}
catch(...){
cout << "error: in reading an event!";
}
}
int main(void){
//read the xml from an input file
std::ifstream ifs("in_file.txt");
std::string xml;
xml.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
//process the xml
process_xml(xml.c_str());
return 0;
}
- 通知:把你的XML转换为有效的XML你必须关闭所有的标签,所以你应该在最后添加
</config>
,因为你在开始时有<config>
。
要运行此代码,您必须从我提供的链接下载rapidxml,并将它解压缩到项目文件夹中。编译不需要额外的标志。
然后,输入文件“in_file.txt”与您纠正XML(*请参阅上面的通知),该代码将产生作为输出:
node->name: config
>>quote
name: text; value:
"Moral indignation is jealous with a halo."
name: author; value:
H.G. Wells
name: livedfrom; value:
1866-1946
name: extrainfo; value:
然后,你可以得到的值存储在变量,结构或任何你想要的。
http://www.xmlsoft.org/ – zzk 2013-03-11 20:07:34
从处理XML文件开始学习C是相当有抱负的。购买一本好的C书并通过第一本书工作。 – 2013-03-11 20:08:54
可能重复的[XML解析器的C](http://stackoverflow.com/questions/399704/xml-parser-for-c) – 2013-03-11 20:12:52