当前位置: 动力学知识库 > 问答 > 编程问答 >

How to parse data from an XML string in C++?

问题描述:

I have a string from a file. For example from a XML file..

I just want to know whats the simplest way to format the content from the following tags?

<member names="John:Frank" family="Smith:Wesson"/>

I just want the John Frank Smith Wesson, each one of them as different strings.

网友答案:

Use a XML parser to parse the xml and then split the values on ':'? Use a parser as RapidXML

网友答案:

In case you like a quick 'n dirty grammar in Boost Spirit:

See it Live on Coliru

#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

int main()
{
    std::string const example = "<member names=\"John:Frank\" family=\"Smith:Wesson\"/>";

    std::vector<std::string> data;

    if (qi::parse(begin(example), end(example).
             *(
                 qi::omit [ *~qi::char_('"') ] >> '"' >> qi::as_string [ *~qi::char_("\":") ] % ':' >> '"'
              ),
             data))
    {
        for (auto const& item : data)
            std::cout << item << "\n";
    }
}

Output

clang++ -std=c++11 main.cpp && ./a.out
John
Frank
Smith
Wesson
网友答案:

I would go with substr combined with finders

  • find the first " position in the string.
  • substring from first place found to first place found starting from last first place. You now have 2 positions, opening and closing "
  • split the resulting string based on : the same way you just did.
  • do it while there's opening and closing " in the string
网友答案:

Your question is all about string manipulation, nothing to XML parsing.

To get the four names from <member names="John:Frank" family="Smith:Wesson"/> is quite easy, you just need:

  1. Treat <member names="John:Frank" family="Smith:Wesson"/> as a string.

  2. Find two big sub-strings based on ", you will get John:Frank and Smith:Wesson.

  3. For each sub-string, further split them based on :, you will get John, Frank, Smith and Wesson. Done!

分享给朋友:
您可能感兴趣的文章:
随机阅读: