| 9617 | {} |
| 9618 | |
| 9619 | void encodeTo( std::ostream& os ) const { |
| 9620 | |
| 9621 | // Apostrophe escaping not necessary if we always use " to write attributes |
| 9622 | // (see: http://www.w3.org/TR/xml/#syntax) |
| 9623 | |
| 9624 | for( std::size_t i = 0; i < m_str.size(); ++ i ) { |
| 9625 | char c = m_str[i]; |
| 9626 | switch( c ) { |
| 9627 | case '<': os << "<"; break; |
| 9628 | case '&': os << "&"; break; |
| 9629 | |
| 9630 | case '>': |
| 9631 | // See: http://www.w3.org/TR/xml/#syntax |
| 9632 | if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' ) |
| 9633 | os << ">"; |
| 9634 | else |
| 9635 | os << c; |
| 9636 | break; |
| 9637 | |
| 9638 | case '\"': |
| 9639 | if( m_forWhat == ForAttributes ) |
| 9640 | os << """; |
| 9641 | else |
| 9642 | os << c; |
| 9643 | break; |
| 9644 | |
| 9645 | default: |
| 9646 | // Escape control chars - based on contribution by @espenalb in PR #465 and |
| 9647 | // by @mrpi PR #588 |
| 9648 | if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) { |
| 9649 | // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 |
| 9650 | os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2) |
| 9651 | << static_cast<int>( c ); |
| 9652 | } |
| 9653 | else |
| 9654 | os << c; |
| 9655 | } |
| 9656 | } |
| 9657 | } |
| 9658 | |
| 9659 | friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { |
| 9660 | xmlEncode.encodeTo( os ); |