前言

  Tinyxml是一个C++跨平台开源库,XML文件切记不要使用Windows记事本打开编辑,最好使用Notepad++进行编辑打开


生成文本

<?xml version="1.0" encoding="UTF-8" ?>
<MyGUI type="Resource" version="1.1" />

代码

TiXmlElement *RootElement = NULL;
 TiXmlDocument *pDoc = NULL;
 pDoc = new TiXmlDocument();
 TiXmlDeclaration *pDeclaration = new TiXmlDeclaration(("1.0"), ("UTF-8"), (""));
 pDoc->LinkEndChild(pDeclaration);
 RootElement = new TiXmlElement(("MyGUI"));
 RootElement->SetAttribute("type", "Resource");
 RootElement->SetAttribute("version", "1.1");
 pDoc->LinkEndChild(RootElement);
 pDoc->SaveFile("fengyuzaitu51cto.xml");
 delete pDoc;


注意:

        tinyxml:Could not load test file Error='Error reading Attributes.'. Exiting.描述:使用windows写字板编辑任何的xml文件,保存成为纯文本文件导致的问题,是下面属性完全消失
Could not load test file 'test.xml'.Error='Error reading Attributes.'. Exiting.


文件读取

<?xml version="1.0" encoding="utf-8"?>
<Organization>
 <Devices>
  <Device id="1000006" type="201">
   <UnitNodes index="0" channelnum="2" >
    <Channel id="1000006$2$0$0" name="TV1"  />
    <Channel id="1000006$2$0$1" name="TV2"  />
   </UnitNodes>
  </Device>
 </Devices>
</Organization>

代码

void IterChannelNode(const TiXmlNode* nodeUnit, std::vector<struChannelInfo> &vecChannelInfo)
{
 const TiXmlNode* nodeChannelIter = NULL;
 nodeChannelIter = nodeUnit->IterateChildren("Channel", nodeChannelIter); do
 {
  if (NULL == nodeChannelIter) break;  std::string strName = nodeChannelIter->ToElement()->Attribute("name");

  struChannelInfo channelInfo;
  channelInfo.strChannelId = nodeChannelIter->ToElement()->Attribute("id");
  channelInfo.strChannelName = nodeChannelIter->ToElement()->Attribute("name");
  vecChannelInfo.push_back(channelInfo);
  nodeChannelIter = nodeChannelIter->NextSibling();
 } while (1);
}void IterUnitNode(const TiXmlNode* nodeDevice, std::vector<struChannelInfo> &vecChannelInfo)
{
 const TiXmlNode* nodeUnitIter = NULL;
 nodeUnitIter = nodeDevice->IterateChildren("UnitNodes", nodeUnitIter);
 do
 {
  if (NULL == nodeUnitIter) break;  IterChannelNode(nodeUnitIter, vecChannelInfo);
  nodeUnitIter = nodeUnitIter->NextSibling();
 } while (1);
}int IterDeviceInfo(const std::string &strXML, std::vector<struChannelInfo> &vecChannelInfo)
{
 if (strXML.empty()) return -1; TiXmlDocument doc;
 doc.LoadFile(strXML.c_str()); TiXmlElement* root = doc.FirstChildElement();
 if (NULL == root) return -1; const TiXmlNode* nodeDevices = NULL;
 nodeDevices = root->IterateChildren("Devices", nodeDevices);
 if (NULL == nodeDevices) return -1; const TiXmlNode* nodeDevice = NULL;
 nodeDevice = nodeDevices->IterateChildren("Device", nodeDevice); do
 {
  if (NULL == nodeDevice) break;
  //访问第一个节点
  std::string strTypeId = nodeDevice->ToElement()->Attribute("type");
  std::cout << strTypeId << std::endl;
  IterUnitNode(nodeDevice, vecChannelInfo);
  nodeDevice = nodeDevice->NextSibling(); } while (1);
 return 0;
}