Read a line from xml file using C++

后端 未结 3 2021
傲寒
傲寒 2020-12-17 06:57

My XML File has:

< Package > xmlMetadata < /Package >

I am searching for a tag in this file and the text between the startin

3条回答
  •  余生分开走
    2020-12-17 07:46

    This is not the way you should parse an XML file, but since you don't want to use a parser library this code might get you started.

    File: demo.xml

    
    
    
       File_Navigate
    
    
    
    
       
          xmlMetadata
       
       
    xmlMetadata.h
    C:\Dependency\xmlMetadata\xmlMetadata.h xmlMetadata.cpp C:\Dependency\xmlMetadata\xmlMetadata.cpp
    xmlMetadata1
    xmlMetadata1.h
    C:\Dependency\xmlMetadata\xmlMetadata1.h xmlMetadata1.cpp C:\Dependency\xmlMetadata\xmlMetadata1.cpp

    The basic idea of the code is while you are reading each line of the file, strip the white spaces that are in the beginning and store the new-stripped-string into tmp, and then try to match it to one of the tags you are looking for. Once you find the begin-tag, keep printing the following lines until the close-tag is found.

    File: parse.cpp

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
        string line;
        ifstream in("demo.xml");
    
        bool begin_tag = false;
        while (getline(in,line))
        {
            std::string tmp; // strip whitespaces from the beginning
            for (int i = 0; i < line.length(); i++)
            {
                if (line[i] == ' ' && tmp.size() == 0)
                {
                }
                else
                {
                    tmp += line[i];
                }
            }
    
            //cout << "-->" << tmp << "<--" << endl;
    
            if (tmp == "")
            {
                //cout << "Found " << endl;
                begin_tag = true;
                continue;
            }
            else if (tmp == "")
            {
                begin_tag = false;
                //cout << "Found " << endl;
            }
    
            if (begin_tag)
            {
                cout << tmp << endl;
            }
        }
    }
    

    Outputs:

    xmlMetadata
    xmlMetadata1
    

提交回复
热议问题