(C++) SplitXml
February 24, 2017 · View on GitHub
(C++) SplitXml
SplitXml is an XML code snippet.
#include <algorithm> #include <cassert> #include <iterator> #include <string> #include <vector> #include <boost/foreach.hpp> ///Split an XML std::string into its parts //From http://www.richelbilderbeek.nl/CppSplitXml.htm const std::vector<std::string> SplitXml(const std::string& s) { std::vector<std::string> v; std::string::const_iterator i = s.begin(); std::string::const_iterator j = s.begin(); const std::string::const_iterator end = s.end(); while (j!=end) { ++j; if ((*j=='>' || *j == '<') && std::distance(i,j) > 1) { std::string t; std::copy( *i=='<' ? i : i+1, *j=='>' ? j+1 : j, std::back_inserter(t)); v.push_back(t); i = j; } } return v; } ///Pretty-print an XML std::string //From http://www.richelbilderbeek.nl/CppXmlToPretty.htm const std::vector<std::string> XmlToPretty(const std::string& s) { std::vector<std::string> v = SplitXml(s); int n = -2; BOOST_FOREACH(std::string& s,v) { assert(!s.empty()); if (s[0] == '<' && s[1] != '/') { n+=2; } s = std::string(n,' ') + s; if (s[n+0] == '<' && s[n+1] == '/') { n-=2; } } return v; }