Attribute Parser

  • + 0 comments

    Did my best to use the clean code advices from "the book". This has actually helped me to debug easily not gonna lie

    #include <cmath>
    #include <cstdio>
    #include <vector>
    #include <iostream>
    #include <algorithm>
    #include <sstream>
    #include <map>
    #include <queue>
    #include <regex>
    
    using namespace std;
    
    void parseOpeningTag(
        string* tag, 
        string* tagChain, 
        map<string, string>* hrmlData
    )
    {
        stringstream ss(*tag);
        string element, attr, value;
        while(!ss.eof())
        {
            ss >> element;
            if(element[0] == '<')
            {
                element = regex_replace(element, regex("<"), "");
                *tagChain += tagChain->empty() 
                    ? element 
                    : "." + element;
            }
            else
            {
                element = regex_replace(element, regex("="), " ");
                stringstream ss(element);
                ss >> attr >> value;
                *tagChain += "~" + attr;
                (*hrmlData)[*tagChain] = value;
                tagChain->erase(tagChain->find("~"));
            }
        }
    }
    
    void parseClosingTag(string* tag, string* tagChain)
    {
        *tag = regex_replace(*tag, regex("</"), "");
        size_t pos = tagChain->find("." + *tag);
        if (pos != std::string::npos) {
            tagChain->erase(pos);
        } 
        else 
        {
            tagChain->erase(tagChain->find(*tag));
        }
    }
    
    void parseHRMLAttributes(
        string* tag, 
        string* tagChain, 
        map<string, string>* hrmlData
    )
    {   
        if((*tag).find("</") == string::npos)
            parseOpeningTag(tag, tagChain, hrmlData);
        
        if((*tag).find("</") != string::npos)
            parseClosingTag(tag, tagChain);
    } 
    
    int main() 
    {
        string line;
        getline(cin, line);
        istringstream iss(line);
        
        int n, q;
        iss >> n >> q;
        
        map<string, string> hrmlData;
        
        /*----------------{Parse HRML}---------------*/
        string tag;
        string tagChain;
        while (n--)
        {
            getline(cin, tag);
            tag = regex_replace(tag, regex(" = "), "=");
            tag = regex_replace(tag, regex("\""), "");
            tag = regex_replace(tag, regex(">"), "");
            parseHRMLAttributes(&tag, &tagChain, &hrmlData);   
        }
    
        /*---------------{Execute Queries}-------------*/
        string query;
        while (q--)
        {
            getline(cin, query);
            if (hrmlData.find(query) == hrmlData.end()) 
            {
                cout << "Not Found!" << endl;
            } 
            else {
                cout << hrmlData[query] << endl;
            }
        }  
        return 0;
    }