之前介绍过tinyxml:
《windows客户端开发–使用tinyxml库解析xml文件》
今天再介绍另一个强大的操作xml的库:
CMarkup
Simple C++ performance for text data and XML
官网:
http://www.firstobject.com/
创建一个xml document:
CMarkup xml;
xml.AddElem( "ORDER" );
xml.IntoElem();
xml.AddElem( "ITEM" );
xml.IntoElem();
xml.AddElem( "SN","132487A-J" );
xml.AddElem( "NAME","crank casing" );
xml.AddElem( "QTY","1" );
结果:
<ORDER>
<ITEM>
<SN>132487A-J</SN>
<NAME>crank casing</NAME>
<QTY>1</QTY>
</ITEM>
</ORDER>
保存:
xml.Save( "C:\\Sample.xml" );
作为字符串返回:
MCD_STR strXML = xml.GetDoc();
加载xml:
xml.Load( "C:\\Sample.xml" );
得到字符串:
xml.SetDoc( strXML );
浏览特定元素:
xml.FindElem(); // root ORDER element
xml.IntoElem(); // inside ORDER
while ( xml.FindElem("ITEM") )
{
xml.IntoElem();
xml.FindElem( "SN" );
MCD_STR strSN = xml.GetData();
xml.FindElem( "QTY" );
int nQty = atoi( MCD_2PCSZ(xml.GetData()) );
xml.OutOfElem();
}
CMarkup xml;
xml.AddElem( "ORDER" );
xml.IntoElem(); // inside ORDER
for ( int nItem=0; nItem<aItems.GetSize(); ++nItem )
{
xml.AddElem( "ITEM" );
xml.IntoElem(); // inside ITEM
xml.AddElem( "SN",aItems[nItem].strSN );
xml.AddElem( "NAME",aItems[nItem].strName );
xml.AddElem( "QTY",aItems[nItem].nQty );
xml.OutOfElem(); // back out to ITEM level
}
xml.AddElem( "SHIPMENT" );
xml.IntoElem(); // inside SHIPMENT
xml.AddElem( "POC" );
xml.SetAttrib( "type",strPOCType );
xml.IntoElem(); // inside POC
xml.AddElem( "NAME",strPOCName );
xml.AddElem( "TEL",strPOCTel );
结果:
<ORDER>
<ITEM>
<SN>132487A-J</SN>
<NAME>crank casing</NAME>
<QTY>1</QTY>
</ITEM>
<ITEM>
<SN>4238764-A</SN>
<NAME>bearing</NAME>
<QTY>15</QTY>
</ITEM>
<SHIPMENT>
<POC type="non-emergency">
<NAME>John Smith</NAME>
<TEL>555-1234</TEL>
</POC>
</SHIPMENT>
</ORDER>
查找元素:
{
xml.IntoElem();
xml.FindElem( "SN" );
MCD_STR strSN = xml.GetData();
xml.ResetMainPos();
xml.FindElem( "QTY" );
int nQty = atoi( MCD_2PCSZ(xml.GetData()) );
xml.OutOfElem();
}
xml.ResetPos(); // top of document
xml.FindElem(); // ORDER element is root
xml.IntoElem(); // inside ORDER
while ( xml.FindElem("ITEM") )
{
xml.FindChildElem( "SN" );
if ( xml.GetChildData() == strFindSN )
break; // found
}
CMarkup与tinyxml对比
参考:
http://www.jb51.cc/article/p-gfhqfbor-tk.html
在使用tinyxml时,可能会new好多对象,但tinyxml的每个对象,在被释放析构时,会将它下面的所有节点都释放点,如TiXmlDocument 文档对象,我们只需要delete doc即可,若是你还delete pElemRoot; delete pElemData,则在运行时会被二次释放报错。
尽量不要在xml中使用中文 TinyXml只认识UTF-8和ISO 8859-1编码,而不知GB2312为何物,但事实上你以GB2312在文档中写入中文,之后可以正确读取,而且文档在记事本中打开也能显示正确的中文,其实这是种巧合,并不是TinyXml支持GB2312了.