Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libxml xmlNodePtr to raw xml string?

Tags:

c

libxml2

Given a valid, arbitrary xmlNodePtr, I would like the string representation of that node, including the tag, attributes, and children in the same form (recursive).

FWIW, my scenario is I am using PerformXPathQuery to get a block of data from within an existing document. I need to get the results of the query, which has nested XML elements in it, as the raw string, so I can insert it into a text field.

These seems like a simple task, however I cannot find an easy way. Writing an xmlDocPtr to file must do this, however, I cannot see a handy method that will do the same thing to an arbitrary node in the tree, and return it in memory.

I hope I am just going blind from the brown-on-brown documentation color scheme at xmlsoft.org

like image 434
Stickley Avatar asked Nov 22 '11 18:11

Stickley


3 Answers

Is xmlNodeDump (or xmlNodeDumpOutput) what you are looking for?

like image 92
Luke Avatar answered Oct 29 '22 17:10

Luke


My code I used to dump a node to a string. It's objectiv-c so just change your output as needed.

xmlBufferPtr buffer = xmlBufferCreate();
int size = xmlNodeDump(buffer, myXMLDoc, myXMLNode, 0, 1);

NSLog(@"%d", size);
NSLog(@"%s", buffer->content);

Don't forget to free your buffer again.

like image 28
lindinax Avatar answered Oct 29 '22 16:10

lindinax


One way you could do it definitely is to create a new document, then use xmlDocCopyNode to copy the node into it and serialize it.

like image 44
kan Avatar answered Oct 29 '22 17:10

kan