gdb/common/xml-utils.c - gdb

Functions defined

Source code

  1. /* Shared helper routines for manipulating XML.

  2.    Copyright (C) 2006-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "common-defs.h"
  15. #include "xml-utils.h"

  16. /* Return a malloc allocated string with special characters from TEXT
  17.    replaced by entity references.  */

  18. char *
  19. xml_escape_text (const char *text)
  20. {
  21.   char *result;
  22.   int i, special;

  23.   /* Compute the length of the result.  */
  24.   for (i = 0, special = 0; text[i] != '\0'; i++)
  25.     switch (text[i])
  26.       {
  27.       case '\'':
  28.       case '\"':
  29.         special += 5;
  30.         break;
  31.       case '&':
  32.         special += 4;
  33.         break;
  34.       case '<':
  35.       case '>':
  36.         special += 3;
  37.         break;
  38.       default:
  39.         break;
  40.       }

  41.   /* Expand the result.  */
  42.   result = xmalloc (i + special + 1);
  43.   for (i = 0, special = 0; text[i] != '\0'; i++)
  44.     switch (text[i])
  45.       {
  46.       case '\'':
  47.         strcpy (result + i + special, "&apos;");
  48.         special += 5;
  49.         break;
  50.       case '\"':
  51.         strcpy (result + i + special, "&quot;");
  52.         special += 5;
  53.         break;
  54.       case '&':
  55.         strcpy (result + i + special, "&amp;");
  56.         special += 4;
  57.         break;
  58.       case '<':
  59.         strcpy (result + i + special, "&lt;");
  60.         special += 3;
  61.         break;
  62.       case '>':
  63.         strcpy (result + i + special, "&gt;");
  64.         special += 3;
  65.         break;
  66.       default:
  67.         result[i + special] = text[i];
  68.         break;
  69.       }
  70.   result[i + special] = '\0';

  71.   return result;
  72. }