6

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

kan
  • 28,279
  • 7
  • 71
  • 101
Stickley
  • 4,561
  • 3
  • 30
  • 29

3 Answers3

9

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.

lindinax
  • 282
  • 2
  • 6
8

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

Luke
  • 11,211
  • 2
  • 27
  • 38
  • Was looking for this quite a while and couldn't get it to work. My returned size had been `-1` and my buffer was `NULL`. Just for anyone as an info: Initialize your buffer! Some examples in the internet are just not correct and the docs are not very detailed in this point either. Use `xmlBufferPtr buffer = xmlBufferCreate();`. – lindinax Jul 24 '13 at 08:18
1

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.

kan
  • 28,279
  • 7
  • 71
  • 101
  • Thanks for the idea. Including the leading tag is definitely sub-optimal. However I tried it with the following and the copy comes up empty : ` for (NSInteger i = 0; i < nodes->nodeNr; i++) { xmlDocPtr partialDoc = xmlNewDoc(BAD_CAST XML_DEFAULT_VERSION); xmlChar *mem; int len; xmlNodePtr copyNode = xmlDocCopyNode( nodes->nodeTab[i], partialDoc, 1 ); xmlAddChild( xmlDocGetRootElement( partialDoc ), copyNode ); xmlDocDumpMemory( partialDoc, &mem, &len ); NSLog( @"%s", mem ); } ` – Stickley Nov 22 '11 at 19:53
  • Sorry, I don't understand if you still have a problem or not. Could you update your question if you have something unclear so far? – kan Nov 22 '11 at 20:58