[ADD] Make and start using an XML encoder

Now, we have basic sanitation!!!!!!
This commit is contained in:
LDA 2024-06-19 02:33:53 +02:00
commit b408cbf224
4 changed files with 110 additions and 19 deletions

View file

@ -1,5 +1,7 @@
#include <XML.h>
#include <string.h>
XMLElement *
XMLDecode(Stream *stream, bool autofree)
{
@ -88,9 +90,90 @@ XMLDecode(Stream *stream, bool autofree)
return ret;
}
void
XMLEncodeString(Stream *stream, char *data)
{
size_t i;
for (i = 0; i < strlen(data); i++)
{
char c = data[i];
if (c == '<')
{
StreamPrintf(stream, "&lt;");
continue;
}
else if (c == '>')
{
StreamPrintf(stream, "&gt;");
continue;
}
else if (c == '&')
{
StreamPrintf(stream, "&amp;");
continue;
}
else if (c == '\'')
{
StreamPrintf(stream, "&apos;");
continue;
}
else if (c == '"')
{
StreamPrintf(stream, "&quot;");
continue;
}
StreamPrintf(stream, "%c", c);
}
}
void
XMLEncodeTag(Stream *stream, XMLElement *element)
{
char *key, *val;
StreamPrintf(stream, "<%s", element->name);
while (HashMapIterate(element->attrs, &key, (void **) &val))
{
StreamPrintf(stream, " %s='", key);
XMLEncodeString(stream, val);
StreamPrintf(stream, "'");
}
if (ArraySize(element->children))
{
size_t i;
XMLElement *child;
StreamPrintf(stream, ">", key, val);
for (i = 0; i < ArraySize(element->children); i++)
{
child = ArrayGet(element->children, i);
XMLEncode(stream, child);
}
StreamPrintf(stream, "</%s>", element->name);
return;
}
StreamPrintf(stream, "/>");
}
void
XMLEncode(Stream *stream, XMLElement *element)
{
/* TODO: Write the entire XML element. This shouldn't be
* too hard. */
if (!stream || !element)
{
return;
}
switch (element->type)
{
case XML_ELEMENT_TAG:
XMLEncodeTag(stream, element);
return;
case XML_ELEMENT_DATA:
XMLEncodeString(stream, element->data);
return;
default:
/* TODO */
break;
}
}