对xml格式的字符串解析
简单实例:
static const char* xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n"
"<file xmlns=\"urn:gsma:params:xml:ns:rcs:rcs:fthttp\" xmlns:am=\"urn:gsma:params:xml:ns:rcs:rcs:rram\">\r\n"
"<file-info type=\"thumbnail\">\r\n"
"<file-size>4800</file-size>\r\n"
"<content-type>image/jpeg</content-type>\r\n"
"<data url=\"http://10.9.119.33/s/3/0045730523.jpg\" until=\"2020-07-16T20:00:44+08:00\" />\r\n"
"</file-info>\r\n"
"<file-info type=\"file\" file-disposition=\"attachment\">\r\n"
"<file-size>4971</file-size>\r\n"
"<file-hash-algorithm>md5</file-hash-algorithm>\r\n"
"<file-hash-value>90:3D:3A:82:70:65:57:69:DE:4E:06:5B:7E:06:34:16</file-hash-value>\r\n"
"<file-name>151bf0195d0ed250b202bd7231a7c509.jpeg</file-name>\r\n"
"<content-type>image/jpeg</content-type>\r\n"
"<data url=\"http://10.9.119.33/s/3/2b681b67-a40a-1038-a6ae-611c59a959a3.jpeg\" until=\"2020-07-16T20:00:44+08:00\" />\r\n"
"</file-info>\r\n"
"</file>\r\n";
int parse_xml_info()
{
XMLDocument doc;
XMLElement* file;
const char *type = 0;
const XMLElement* p;
XMLError err;
XMLError queryResult;
unsigned long long file_size = 0;
const char *origFileName = 0;
const char *contentType = 0;
bool found = false;
err = doc.Parse(xml);
if (err){
printf("parse_xml_info: Parse err\n");
return -1;
}
file = doc.FirstChildElement("file");
if (!file){
printf("parse_xml_info: FirstChildElement file err\n");
return -1;
}
for (p = file->FirstChildElement("file-info"); p; p = p->NextSiblingElement("file-info")) {
queryResult = p->QueryStringAttribute("type", &type);
if (queryResult == XML_SUCCESS){
if (strncmp("file", type, 4) == 0){
p->FirstChildElement("file-size")->QueryUnsigned64Text(&file_size);
contentType = p->FirstChildElement("content-type")->GetText();
p->FirstChildElement("data")->QueryStringAttribute("url", &origFileName);
found = true;
break;
}
}
}
if (!found){
printf("parse_xml_info: file-info Attribute(type) not found \'file\' \n");
return -1;
}
printf("parse_xml_info: file_size:%u content_type:%s origFileName:%s",
file_size, contentType, origFileName);
return 0;
}
网友评论