I am using libxml in C and this is how I create xml:
xmlDocPtr createXmlSegment(char *headerContent, char *dataContent)
{
xmlDocPtr doc;
doc = xmlNewDoc(BAD_CAST "1.0");
xmlNodePtr rdt, header, data;
rdt = xmlNewNode(NULL, BAD_CAST "rdt-segment");
xmlSetProp(rdt, "id", "1");
header = xmlNewNode(NULL,BAD_CAST "header");
data = xmlNewNode(NULL, BAD_CAST "data");
xmlNodeSetContent(header, BAD_CAST headerContent);
xmlNodeSetContent(data, BAD_CAST dataContent);
xmlAddChild(rdt, header);
xmlAddChild(rdt, data);
xmlDocSetRootElement(doc, rdt);
return doc;
}
and this is how I want get data from that xml:
int getDataFromXmlSegment(char *data, char *header, char *content)
{
xmlDocPtr doc = xmlReadMemory(data, strlen(data), NULL, NULL, XML_PARSE_NOBLANKS);
xmlNode *rdt = doc->children;
xmlNode *headerNode = rdt->children;
header = (char *)headerNode->content;
content = (char *)headerNode->next->content;
printf("header: %s, content: %s", header, content);
return EXIT_SUCCESS;
}
When I test headerNode->name or ->next->name then the names are correct (it´s names of that elements) but content returns null. Anyone knows where is problem?
Short answer: use xmlNodeGetContent.
Element nodes themselves don't contain content. Instead, they have children text nodes, and those contain content. The contents of an element may be a mix of text and tags, and this allows it to maintain the ordering, represent entities, etc.
You could iterate over the child nodes and look at THEIR content members, but xmlNodeGetContent does that for you, and will handle child tags and entities properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With