xml_escape_parser.cpp

Go to the documentation of this file.
00001 /*---------------------------------------------------------------------\
00002 |                          ____ _   __ __ ___                          |
00003 |                         |__  / \ / / . \ . \                         |
00004 |                           / / \ V /|  _/  _/                         |
00005 |                          / /__ | | | | | |                           |
00006 |                         /_____||_| |_| |_|                           |
00007 |                                                                      |
00008 \---------------------------------------------------------------------*/
00013 #include <string>
00014 #include "xml_escape_parser.hpp"
00015 
00016 namespace iobind{
00017 namespace parser{
00018 
00019 std::string xml_escape_parser::escape(const std::string &istr) const
00020 {
00021   typedef unsigned char uchar;
00022 
00023   std::string str( istr );
00024   for ( size_t i = 0; i < str.size(); ++i )
00025     {
00026       switch (str[i])
00027         {
00028           case '<': str.replace(i, 1, "&lt;"); i += 3; break;
00029           case '>': str.replace(i, 1, "&gt;"); i += 3; break;
00030           case '&': str.replace(i, 1, "&amp;"); i += 4; break;
00031           case '"': str.replace(i, 1, "&quot;"); i += 5; break;
00032           case '\'': str.replace(i, 1, "&apos;"); i += 5; break;
00033 
00034           // control chars we allow:
00035           case '\n':
00036           case '\r':
00037           case '\t':
00038             break;
00039 
00040           default:
00041             if ( uchar(str[i]) < 32u )
00042               str[i] = '?'; // filter problematic control chars (XML1.0)
00043               break;
00044         }
00045     }
00046   return str;
00047 }
00048 
00049 std::string xml_escape_parser::unescape(const std::string &istr) const
00050 {
00051   size_t i;
00052   std::string str = istr;
00053   i = str.find_first_of("&");
00054   while (i != std::string::npos)
00055     {
00056       if (str[i] == '&')
00057         {
00058           if (!str.compare(i + 1, 3, "lt;"))
00059             str.replace(i, 4, 1, '<');
00060           else if (!str.compare(i + 1, 3, "gt;"))
00061             str.replace(i, 4, 1, '>');
00062           else if (!str.compare(i + 1, 4, "amp;"))
00063             str.replace(i, 5, 1, '&');
00064           else if (!str.compare(i + 1, 5, "apos;"))
00065             str.replace(i, 6, 1, '\'');
00066           else if (!str.compare(i + 1, 5, "quot;"))
00067             str.replace(i, 6, 1, '"');
00068         }
00069       i = str.find_first_of("&", i + 1);
00070     }
00071   return str;
00072 }
00073 }; // parser
00074 }; // iobind

doxygen