Write Base64 encoded text node with libxml2
I have not found a proper tutorial on libxml2 yet and thus I'm st开发者_运维百科ruggling with some basic concepts, having "only" the API docs at hand, which are, IMHO, a little too brief in some points.
This is (C++) my attempt to write Base64 encoded data to a document (a text node as a child of the root element):
// create doc and root node
xmlDocPtr doc = xmlNewDoc( (xmlChar*) "1.0" );
xmlNodePtr root_node = xmlNewNode( 0, (xmlChar*) "root" );
xmlDocSetRootElement( doc, root_node );
// create text node and write data
xmlNodePtr node = xmlNewDocText( doc, (xmlChar*) "" );
xmlAddChild( root_node, node );
xmlTextWriterPtr writer = xmlNewTextWriterTree( doc, node, 0 );
xmlTextWriterWriteBase64( writer, "asdf", 0, 4 );
The following is just doing test output:
// get textual representation
xmlChar *mem = 0;
int size = 0;
xmlDocDumpFormatMemory( doc, &mem, &size, 1 );
if ( mem ) {
std::cout << mem << std::endl;
}
Unfortunately, the text node does not appear in the output.
I'd be thankful for a solution to this problem and some links to introductory material regarding libxml2.
It appears that xmlTextWriterWriteBase64() needs the context of where to put the text. I was able to add the text to a new element via xmlTextWriterStartElement(), xmlTextWriterWriteBase64(), and xmlTextWriterEndElement(). You would think giving a node to xmlNewTextWriterTree() would set the context, but apparently it does not. The "documentation" for libxml is just terrible (even the sample applications); they give you the how, but not the why. I don't really know of any good documentation; I just figured most of it out by myself through trial and error (sad).
精彩评论