#include "pugixml.hpp"
#include <string>
#include <iostream>
#include <cstring>
struct xml_string_writer: pugi::xml_writer
{
virtual void write(
const void* data,
size_t size)
{
result.append(static_cast<const char*>(data), size);
}
};
struct xml_memory_writer: pugi::xml_writer
{
size_t capacity;
xml_memory_writer(): buffer(0), capacity(0), result(0)
{
}
xml_memory_writer(char* buffer, size_t capacity): buffer(buffer), capacity(capacity), result(0)
{
}
size_t written_size() const
{
return result < capacity ? result : capacity;
}
virtual void write(
const void* data,
size_t size)
{
if (result < capacity)
{
size_t chunk = (capacity - result <
size) ? capacity - result : size;
memcpy(buffer + result, data, chunk);
}
}
};
{
xml_string_writer writer;
node.print(writer);
return writer.result;
}
char* node_to_buffer(pugi::xml_node node,
char* buffer,
size_t size)
{
xml_memory_writer writer(buffer, size - 1);
node.print(writer);
buffer[writer.written_size()] = 0;
}
char* node_to_buffer_heap(pugi::xml_node node)
{
xml_memory_writer counter;
node.print(counter);
char* buffer = new char[counter.result + 1];
xml_memory_writer writer(buffer, counter.result);
node.print(writer);
buffer[writer.written_size()] = 0;
}
int main()
{
doc.load_string("<foo bar='baz'>hey</foo>");
std::cout << "contents: [" << node_to_string(doc) << "]\n";
char large_buf[128];
std::cout << "contents: [" << node_to_buffer(doc, large_buf, sizeof(large_buf)) << "]\n";
char small_buf[22];
std::cout << "contents: [" << node_to_buffer(doc, small_buf, sizeof(small_buf)) << "]\n";
char* heap_buf = node_to_buffer_heap(doc);
std::cout << "contents: [" << heap_buf << "]\n";
delete[] heap_buf;
}