Hi Guys,
I'm trying to clean up an xml file that has unnecessary elements in it using CPP.
e.g from the following line..
<xd ref="hgfhgfhj" invisible="true" name="bob" age="45" species="vlergan" />
The contents between the quotes can vary, so the idea would be to remove, for example,ref="hgfhgfhj". Given that the contents of the quotes will vary, there is no simple find string and erase that can be used. It looks like I need to..
Search for ref=", get the start position, get the end position, start a search for " at the previous search results end position, then erase between those two points.
The problem I have is that .erase doesn't use start and end positions, only a start position, and length. mainStr.erase(pos, toErase.length());
My original workaround for this was to find the next " and set position in pos2, then just do an int eraselength = pos2-pos; to get a length.
mainStr.erase(pos, eraselength); but .erase doesn't accept an integer for the length.
If any folks out there could give me a tip on this i'd be very grateful as there don't seem to be any examples out there that I can find that relate to this kind of erase use. Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
#include "pch.h"
#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <functional>
#include <stdio.h>
#include <vector>
void eraseAllSubStr(std::string & mainStr, const std::string & toErase);
int main()
{
std::string STRING;
std::ifstream infile;
infile.open("C:\\test\\myxml.xml");
while (!infile.eof()) // To get you all the lines.
{
getline(infile, STRING); // Saves the line in STRING.
eraseAllSubStr(STRING, "visible=\"");
//eraseSubStringsPre(STRING, { "visible=\"true\"","version=\"1\"","version=\"2\"","version=\"3\"","version=\"4\"" });
std::cout << STRING <<"\n"; // Prints our STRING.
}
infile.close();
system("pause");
return 0;
}
void eraseAllSubStr(std::string & mainStr, const std::string & toErase)
{
size_t pos = std::string::npos;
// Search for the substring in string in a loop untill nothing is found
while ((pos = mainStr.find(toErase)) != std::string::npos)
{
//find the next instance of " after string
// If found then erase it from string
mainStr.erase(pos, toErase.length());
}
}
/*
void eraseSubStringsPre(std::string & mainStr, const std::vector<std::string> & strList)
{
// Iterate over the given list of substrings. For each substring call eraseAllSubStr() to
// remove its all occurrences from main string.
for (std::vector<std::string>::const_iterator it = strList.begin(); it != strList.end(); it++)
{
eraseAllSubStr(mainStr, *it);
}
}*/
|