libxml xmlNodePtr to raw xml string?

2020-02-07 03:16发布

问题:

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

回答1:

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



回答2:

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.



回答3:

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.



标签: c libxml2