| 9816 | {} |
| 9817 | |
| 9818 | void encodeTo( std::ostream& os ) const { |
| 9819 | |
| 9820 | // Apostrophe escaping not necessary if we always use " to write attributes |
| 9821 | // (see: http://www.w3.org/TR/xml/#syntax) |
| 9822 | |
| 9823 | for( std::size_t i = 0; i < m_str.size(); ++ i ) { |
| 9824 | char c = m_str[i]; |
| 9825 | switch( c ) { |
| 9826 | case '<': os << "<"; break; |
| 9827 | case '&': os << "&"; break; |
| 9828 | |
| 9829 | case '>': |
| 9830 | // See: http://www.w3.org/TR/xml/#syntax |
| 9831 | if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' ) |
| 9832 | os << ">"; |
| 9833 | else |
| 9834 | os << c; |
| 9835 | break; |
| 9836 | |
| 9837 | case '\"': |
| 9838 | if( m_forWhat == ForAttributes ) |
| 9839 | os << """; |
| 9840 | else |
| 9841 | os << c; |
| 9842 | break; |
| 9843 | |
| 9844 | default: |
| 9845 | // Escape control chars - based on contribution by @espenalb in PR #465 and |
| 9846 | // by @mrpi PR #588 |
| 9847 | if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) { |
| 9848 | // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 |
| 9849 | os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2) |
| 9850 | << static_cast<int>( c ); |
| 9851 | } |
| 9852 | else |
| 9853 | os << c; |
| 9854 | } |
| 9855 | } |
| 9856 | } |
| 9857 | |
| 9858 | friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { |
| 9859 | xmlEncode.encodeTo( os ); |