无法使用libxml2读取XML节点的内容

时间:2012-07-09 11:21:35

标签: libxml2

我只想读取之前写过文件的XML节点内容中的字符串。这是代码:

int main() {

xmlNodePtr n, n2, n3;
xmlDocPtr doc;
xmlChar *xmlbuff;
int buffersize;
xmlChar* key;

doc = xmlNewDoc(BAD_CAST "1.0");
n = xmlNewNode(NULL, BAD_CAST "root");


xmlNodeSetContent(n, BAD_CAST "test1");
n2 = xmlNewNode(NULL, BAD_CAST "devices");
xmlNodeSetContent(n2, BAD_CAST "test2");
n3 = xmlNewNode(NULL, BAD_CAST "device");
xmlNodeSetContent(n3, BAD_CAST "test3");

//n2 = xmlDocCopyNode(n2, doc, 1);
xmlAddChild(n2,n3);
xmlAddChild(n,n2);


xmlDocSetRootElement(doc, n);


xmlSaveFormatFileEnc( FILENAME, doc, "utf-8", 1 );

doc = xmlParseFile(FILENAME);
n = xmlDocGetRootElement(doc);

key = xmlNodeListGetString(doc, n, 1);
printf("keyword: %s\n", key);
xmlFree(key);

n = n->children;

key = xmlNodeListGetString(doc, n, 1);
printf("keyword: %s\n", key);
xmlFree(key);

n = n->children;

key = xmlNodeListGetString(doc, n, 1);
printf("keyword: %s\n", key);
xmlFree(key);

n2 = xmlNewNode(NULL, BAD_CAST "address");
xmlAddChild(n,n2);

xmlDocSetRootElement(doc, n);

xmlSaveFormatFileEnc( FILENAME, doc, "utf-8", 1 );

return 0;
}

此代码的输出是 - > keyword :( null) keyword:test1 keyword:(null)

为什么我不能阅读test2和test3?

提前致谢。

1 个答案:

答案 0 :(得分:1)

您正在生成的XML文件是:

<?xml version="1.0" encoding="utf-8"?>
<root>
    test1
    <devices>
        test2
        <device>
            test3
        </device>
    </devices>
</root>

在libxml中,子节点包含文本节点和元素。您需要检查类型字段以了解节点指向的内容。

以下是您可以使用的代码(我确定有更好的方法可以执行此操作,但它清楚地显示了您应该执行的类型测试)。我使用n表示元素节点,使用n2表示搜索文本节点。

// Get <root>    
n = xmlDocGetRootElement(doc);
n2 = n -> children;
while (n2 != NULL && n2 -> type != XML_TEXT_NODE)
    n2 = n2 -> next;
if (n2 != NULL)
{
   key = xmlNodeListGetString(doc, n2, 1);
   printf("keyword: %s\n", key);
   xmlFree(key);
}

// grab child
n = n -> children;
while (n != NULL && n -> type != XML_ELEMENT_NODE)
    n = n -> next;
if (n == NULL)
    return -1;

// grab its 1st text child       
n2 = n -> children;
while (n2 != NULL && n2 -> type != XML_TEXT_NODE)
    n2 = n2 -> next;
if (n2 != NULL)
{
   key = xmlNodeListGetString(doc, n2, 1);
   printf("keyword: %s\n", key);
   xmlFree(key);
}

// grab child
n = n -> children;
while (n != NULL && n -> type != XML_ELEMENT_NODE)
    n = n -> next;
if (n == NULL)
    return -1;

// grab its 1st text child       
n2 = n -> children;
while (n2 != NULL && n2 -> type != XML_TEXT_NODE)
    n2 = n2 -> next;
if (n2 != NULL)
{
   key = xmlNodeListGetString(doc, n2, 1);
   printf("keyword: %s\n", key);
   xmlFree(key);
}
相关问题