leon22
leon22

Reputation: 5669

Remove all xml tags from a std::string

I have a std::string xmlString = "<out><return>Hello</return></out>" and I want to remove all of the tags! (without an additional library, except tinyXML -> already loaded)

result -> Hello

Thx

Upvotes: 3

Views: 1906

Answers (3)

leon22
leon22

Reputation: 5669

Possible solution:

std::string ClassA::ParseXMLOutput(std::string &xmlBuffer)
{
    bool copy = true;
    std::string plainString = "";   
    std::stringstream convertStream;

    // remove all xml tags
    for (int i=0; i < xmlBuffer.length(); i++)
    {                   
        convertStream << xmlBuffer[i];

        if(convertStream.str().compare("<") == 0) copy = false;
        else if(convertStream.str().compare(">") == 0) 
        {
            copy = true;
            convertStream.str(std::string());
            continue;
        }

        if(copy) plainString.append(convertStream.str());       

        convertStream.str(std::string());
    }

    return plainString;
}

Upvotes: 3

Dmitry Ledentsov
Dmitry Ledentsov

Reputation: 3660

If you already use tinyXML, iterate over all nodes depth-first and append the text of the node to the string you're building. There are some answers of SO on how to do that, i.e. TinyXML Iterating over a Subtree

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409442

If your compiler and standard library support the new C++11 regular expressions you might be able to use std::regex_replace.

There are also other regular expression libraries you could use.

If you don't want to use regular expressions, then you could manually copy the string, while checking for "tags". When you see a '<' just continue looping without copying until you see a '>'.

Upvotes: 3

Related Questions