-6

I have to parse a TXT file of XML messages and save the ID value in another file. I can reach up to the <ID> tag using find function. But how to get the value, also the length of value varies.

<note>
    <to>Tove</to>
    <from>Jani</from>
    <ID>Fx12345</ID>
    <body>Don't forget me this weekend!</body>
</note>
<note>
    <to>Tove</to>
    <from>Alex</from>
    <ID>Fx1236785</ID>
    <body>Don't forget me this weekend!</body>
</note>

I'm using this approach

while (!fileInput.eof()) {
   getline(fileInput, line);
    if ((offset = line.find("<ID>", 0)) != string::npos) {
        // How to get only value
    }
}
NetVipeC
  • 4,402
  • 1
  • 17
  • 19
Abhi
  • 3
  • 1

1 Answers1

4

string::find() has an overload that specifies the position to start the search. So simply start a second search, starting at the end of <ID>, to look for </ID>. You are after what comes in between the two. Pretty simple really.

However, as suggested elsewhere, there are a lot of XML parsers out there. Using a full XML parser would be recommended if the input file could have some variations.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466