您的位置:首页 > 其它

xml数据和xml文件的解析

2013-10-14 17:33 190 查看
tinyxml能读写内存中的xml

用cstring来构造和传递xml数据以方便进行通讯,即从内存解析XML的tinyxml

以下实例

从内存中解析用TiXmlDocument的Parse函数

从xml文件中解析用TiXmlDocument的LoadFile函数

------解决方案--------------------------------------------------------

#pragma once

#include<string>

#include "tinyxml.h"

using namespace std;

class CXML

{

public:

CXML(void){}

~CXML(void){}

private:

TiXmlDocument m_xml;

TiXmlElement* pElement;

private:

TiXmlElement* getFirstElement(string ElementMark,TiXmlElement* pcrElement);

public:

//解析xml字符串

int ParseXmlStr(string xmlstr);

//解析xml文件

int ParseXmlFile(string xmlFile);

//取得属性值

int getElementAttributeValue(string AttributeName,string& value);

//根据标签取值

int getFirstElementValue(string ElementMark,string& value);

//针对同一标签的记录取值,如果返回值是0表明再无此标签内容值可取

int getNextElementValue(string ElementMark,string& value);

//获取根结点

TiXmlElement* getRootElement();

//返回当前的xml字符串

string getXmlStr();

//清空解析的内容

void Clear();

//添加子节点

TiXmlElement* addXmlRootElement(string ElementMark);//添加一个根节点

//添加子节点

TiXmlElement* addXmlChildElement(TiXmlElement* pElement,string ElementMark);

//给节点添加值

void addElementValue(TiXmlElement* pElement,string value);

//添加属性及属性值

void addXmlAttribute(TiXmlElement* pElement,string AttributeMark,string value);

//添加声明

void addXmlDeclaration(string vesion,string encoding,string standalone);

//添加注释

void addXmlComment(TiXmlElement* pElement,string Comment);

//将xml内容保存到文件

void saveFile(string FileName);

};

可以自己封装,将string类型换成CString类型。

///////////////////实现文件

#include "stdafx.h"

#include "XML.h"

////////////////////////////////////////////////////

int CXML::ParseXmlFile(string xmlFile)

{

int result=0;

try

{

if(m_xml.LoadFile(xmlFile.c_str()))

result=1;

else

result=0;

}

catch(...)

{

}

return result;

}

////////////////////////////////////

int CXML::ParseXmlStr(std::string xmlStr)

{

int result=0;

if(xmlStr=="")

return 0;

try

{

if(m_xml.Parse(xmlStr.c_str()))

result=1;

else

result=0;

}

catch(...)

{

}

return result;

}

.

.

.

.

.

.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: