从XML文件中提取时间戳

时间:2015-11-22 03:24:55

标签: c++ xml

我应该从以下XML文档中提取时间戳,并将时间戳输出到输出文件。但是,到目前为止我创建的内容除了提取前面的代码时还提取时间戳,当我只想要时间戳时(例如:timestamp =" 2014-07-08T18:14:16.468Z" )。有人可以指出我做错了什么吗?提前谢谢!

XML文档:http://pastebin.com/DLVF0cXY

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
string tempStr;

ifstream inFile;
ofstream outFile;
outFile.open("Outputdata.txt");
inFile.open("Groupproject.xml");
if (inFile.fail()) {
    cout << "Error Opening File" << endl;
    system("pause");
    exit(1);
}
while (inFile) {
    inFile >> tempStr;
    if (tempStr.find('Z\"') != string::npos) {
        cout << "Found timestamp" << tempStr;
        outFile << tempStr << endl;
        cout << "Copied to file" << endl;
    }
}
inFile.close();
outFile.close();
system("pause");
return 0;
}

2 个答案:

答案 0 :(得分:0)

获得std::string后,您可以使用它的成员函数来查找时间戳字段的出现位置。使用find获取时间戳字段的开头并查找结尾。然后使用substr函数提取正确的字符。

答案 1 :(得分:0)

正如Anon Mail建议的那样如果您尝试使用不同的参数解析整个.xml文件,我建议您使用xml库,例如rapidxml或tinyxml。但是出于问题的目的,我已经包含了一个应该有效的代码版本。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
using namespace std;
string tempStr;
// escaped double qoute.
string findStr = "timestamp=\""

ifstream inFile;
ofstream outFile;
outFile.open("Outputdata.txt");
inFile.open("Groupproject.xml");
if (inFile.fail()) {
    cout << "Error Opening File" << endl;
    system("pause");
    exit(1);
}

size_t found;

while (inFile) {
    getline(inFile,tempStr);
    found = tempStr.find(findStr);
    if (found!=std::string::npos)
    {
        break;
    }
}

// Erases from beggining to end of timestamp="
tempStr.erase(tempStr.begin(),(found + tempStr.length()));

// Finds index of next double qoute.
found = tempStr.findStr("\"");

if (found=std::string::npos)
{
    cerr << "Could not find matching qoute:";
    exit(1);
}

// Erases from matching qoute to the end of the string.
tempStr.erase(found, tempStr.end());

cout << "timestamp found" << tempStr << "Saving to outFile" <<  endl;

outFile << tempStr;

inFile.close();
outFile.close();
system("pause");
return 0;
}
相关问题