tcp接收xml数据解析

避免tcp接收xml数据时加上xml数据长度,根据xml数据特点来解析recv到的xml数据

 int nPos1 = 0;

 int nPos2 = 0;

 int nTempPos = 0;

 int nXmlParseStep = 0;

 std::string strRequest;

 std::string strXmlNode;

 char szXmlData[1024] = {0};



strcpy(szXmlData, "<?xml version=\"1.0\"?><Alarmstatus Num=1><Item><DeviceID></DeviceID><DutyStatus>OFFDUTY</DutyStatus></Item></Alarmstatus>");



int nXmlLen = strlen(szXmlData);



 strRequest += std::string(szXmlData, nXmlLen);

 if(nXmlParseStep == 0)       //找到xml header <?xml version="1.0"?>

 {

   nPos1 = strRequest.find("<?", 0);

   if(nPos1 != std::string::npos)

   {

    nPos2 = strRequest.find("?>", nPos1+1);

    if(nPos2 != std::string::npos)

     nXmlParseStep = 1;

   }

 }

  

 if(nXmlParseStep == 1)

 {

   nPos1 = strRequest.find("<", nPos2+1);

   if(nPos1 != std::string::npos)

   {

    nPos2 = strRequest.find(">", nPos1+1);

    if(nPos2 != std::string::npos)

    {

     nXmlParseStep = 2;

     nTempPos = strRequest.find(" ", nPos1+1);      //避免有子属性,如<Alarmstatus Num=1>

     if(nTempPos  == std::string::npos)

      strXmlNode = strRequest.substr(nPos1+1, nPos2-nPos1-1);

     else

      strXmlNode = strRequest.substr(nPos1+1, nTempPos-nPos1-1);

    }

   }

 }

  

 if(nXmlParseStep == 2)

 {

   nPos1 = strRequest.find("</"+strXmlNode+">", nPos2+1);

   if(nPos1 != std::string::npos)

   {

    nXmlParseStep = 0;

    nPos1 = nPos2 = 0;

    strRequest.erase(0, std::string::npos);

   }

 }


 

 

你可能感兴趣的:(xml)