简体   繁体   中英

Reading XML file in c++

I am trying to read an xml file in c++ without using any c++ libraries. I have taken code from another post and tried to understand and implement it. So far I have this...

{
    string line;
    ifstream in("Team.xml");

    bool startOfTag;
    startOfTag = false;

    while (getline(in,line))
    {
        std::string temp; 
        for (int i = 0; i < line.length(); i++)
        {
            if (line[i] == ' ' && temp.size() == 0)
            {
            }
            else
            {
                temp += line[i];
            }
        }

        cout << "-->" << temp << "<--" << endl;

        if (temp == "<Fname>")
        {
            cout << "Found <Fname>" << endl;
            startOfTag = true;
            continue;
        }
        else if (temp == "</Fname>")
        {
            startOfTag = false;
            cout << "Found </Fname>" << endl;
        }

        if (startOfTag)
        {
            cout << temp << endl;
        }
    }
}

then, I have my xml file looking like this.

<?xml version="1.0" ?>

<Team>
    <Player>
        <Fname>David</Fname>
        <Lname>James</Lname>
    </Player>
</Team>

At this moment in time, I am only wanting to read the values within <Fname> ie David but when running the program this I the entire xml contents. Any ideas?

I suggest you follow the syntax and grammar as defined by the XML specification:

XML Spec.

You should also invest in a debugger or if your IDE supports breakpoints and single stepping, use it.

I don't understand what your for loop is trying to accomplish.
If you are going to parse a language, do it properly. Look up "how to parse" or "lexical analysis".

The following methods of std::string may be of use:

find
substr
find_first_not_of (good for skipping whitespace)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM