如何获取libxml2的内容?

Ale*_*lex 2 c++ libxml2

我正在使用libxml2和C++.以下功能在此处崩溃return (char*)cur->content;.当我将其更改return (char*)cur->name;为时,它将返回attribute哪个是标签的名称.我想要的是1,2和3(基于C++代码下面的XML文件).我究竟做错了什么?

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;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

它正在解析的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>
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 7

我发现应该return (char*)cur->children->content;通过反复试验.

  • 节点的内容是该节点的子节点,这就是您必须首先访问子节点的原因.您也可以考虑使用xmlNodeGetContent函数而不是直接访问结构.也就是说,"return(char*)xmlNodeGetContent(cur-> children);". (2认同)