libxml2的不容获得节点内容 [英] libxml2 can´t get content from node
问题描述
我用的用C的libxml,这是我如何创建XML:
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;
}
这是我多么希望得到从XML数据:
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;
}
当我测试headerNode->名称或 - >下一步 - >名称,则名称是正确的(即汇入作业元素的名称),但内容返回null。任何人都知道在哪里的问题?
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?
推荐答案
简短的回答:使用 xmlNodeGetContent
元素节点本身不包含的内容。相反,他们有孩子文本节点,以及那些包含内容。元素的内容可以是文本和标记的混合,这使得它保持排序,再present实体等。
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.
您可以遍历子节点,并期待在他们的内容成员,但xmlNodeGetContent会替你,会处理子标签和实体正确的。
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.
这篇关于libxml2的不容获得节点内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!