如何使用libxml2获取内容?

3
我正在使用libxml2和C++。下面的函数在return (char*)cur->content;处崩溃。当我将其更改为return (char*)cur->name;时,它将返回标签的名称attribute。我想要的是1、2和3(基于下面的XML文件和C++代码)。我做错了什么?
char* xml2sdf::getId(xmlNode* part){

    xmlNode* cur = part->xmlChildrenNode;

    // get the id
    while (cur != NULL) {

        if ( !xmlStrcmp(cur->name, (const xmlChar *)"attribute") ) {
            xmlAttrPtr attr = cur->properties;

            if( !xmlStrcmp( attr->children->content, (const xmlChar*)"id" ) ){
                return (char*)cur->content;
            }
        }

        cur = cur->next;
        }

    }
}

正在解析的XML文件部分:

<part ref="part10" name="part10">
    <attribute name="face">7</attribute>
    <attribute name="id">1</attribute>
</part>

<part ref="part20" name="part20">
    <attribute name="face">5</attribute>
    <attribute name="id">2</attribute>
</part>

<part ref="part30" name="part30">
    <attribute name="face">9</attribute>
    <attribute name="id">3</attribute>
</part>
1个回答

8
我通过试错发现应该是return (char*)cur->children->content;

2
节点的内容是该节点的子元素,因此必须首先访问子元素。您还可以考虑使用xmlNodeGetContent函数而不是直接访问结构。例如:"return (char*)xmlNodeGetContent( cur->children );"。 - Ishmael
另一个选项是使用(char*)XML_GET_CONTENT(cur->children)宏,它会对空指针进行额外的检查。 - Giovanni Cerretani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接