Search code examples
c++cxmlxml-parsingbarcode

How to extract a perticular data from xml whole output data in C++


I have a C++ function which prints whole xml output data on console. This data has many elements. I want to print particular element on the console.

My function looks like below:

 void SampleEventListner::OnBarcodeEvent(short int eventType, std::string & pscandata){
    cout << pscandata << endl;
}

This above code is printing output like the attached photo. Out of many elements i need to print only datalabel. How can we do this?. Thank you.enter image description here


Solution

  • I like to use pugixml; small lightweight and fast.

    #include <iostream>
    #include "pugixml.hpp"
    
    std::string XML = "<outArgs>\
      <scannerID>1</scannerID>\
      <arg-xml>\
        <scandata>\
          <modelnumber>DS9308-SR00004ZZWW</modelnumber>\
          <serialnumber>19361523701373 </serialnumber>\
          <datalabel>0x68 0x74 0x68 0x74 0x68 0x74 0x68 0x74 0x68 0x74 0x68 0x74 0x68 0x74</datalabel>\
          <rawdata>0x00 0x01 0x00 0x01 0x00 0x01 0x00 0x01 0x00 0x01 0x00 0x01 0x00 0x01</rawdata>\
        </scandata>\
      </arg-xml>\
    </outArgs>";
    
    void PrintTag(std::string &pscandata)
    {
      pugi::xml_document DOM = pugi::xml_document();
      pugi::xml_parse_result result = DOM.load_string(pscandata.c_str(), pugi::parse_default);
      if (result)
        std::cout << DOM.select_node("//datalabel").node().first_child().value() << "\n";
      else
        std::cout << "Error parsing XML. Offset:" << result.offset;
    }
    
    int main(int argc, char *argv[])
    {
      PrintTag(XML);
    }