libxml2 can´t get content from node

霸气de小男生 提交于 2020-01-02 02:05:13

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10363380/libxml2-can%c2%b4t-get-content-from-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!