Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libxml2 can´t get content from node

Tags:

c

xml

libxml2

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?

like image 718
Libor Zapletal Avatar asked Apr 28 '12 12:04

Libor Zapletal


1 Answers

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.

like image 73
Jason Viers Avatar answered Oct 25 '22 12:10

Jason Viers