[libxml2]_[C/C++]_[使用libxml2读取内存的xml片段]


场景:

1.有时候需要读取其他的xml片段输出组合成一个完整的xml文档.

2.或者对内存xml进行修改.


void ReadXmlFromMemory()
{
	string source =
			"<margin left=\"19\"><font size=\"10\" type=\"Courier\"> 1984 By George Orwell</font></margin>";
	string dest;
	xmlTextReaderPtr reader = xmlReaderForMemory(source.c_str(), source.size(),
			NULL, NULL, 0);
	int ret = xmlTextReaderRead(reader);
	while (ret == 1)
	{
		xmlNodePtr node = xmlTextReaderCurrentNode(reader);
		if (!xmlStrcmp(node->name, BAD_CAST "margin"))
		{
			xmlChar* left_attr = xmlGetProp(node, BAD_CAST "left");
			cout << "left: " << (char*) left_attr << endl;
			xmlFree(left_attr);
		}

		cout << "node name is: " << node->name << endl;
		if (!xmlStrcmp(node->name, BAD_CAST "font"))
		{
			xmlChar* size_attr = xmlGetProp(node, BAD_CAST "size");
			cout << "size_attr: " << (char*) size_attr << endl;
			xmlFree(size_attr);
			xmlChar* type_attr = xmlGetProp(node, BAD_CAST "type");
			cout << "type_attr: " << (char*) type_attr << endl;
			xmlFree(type_attr);

		}
		if (!xmlStrcmp(node->name, BAD_CAST "text"))
		{
			cout << "node content is: " << node->content << endl;
			dest.append((char*) node->content);
			break;
		}
		ret = xmlTextReaderRead(reader);
		cout << "loop" << endl;
	}
	cout << "bytes readed: " << xmlTextReaderByteConsumed(reader) << endl;
	xmlTextReaderClose(reader);
	xmlFreeTextReader(reader);
	cout << "dest: " << dest << endl;

	//初始化和释放暂时不用管
//	xmlInitParser();
	//xmlCleanupParser();
	//xmlMemoryDump();
}


你可能感兴趣的:(c,libxml2,内存xml字符串)