How to get attributes from a node in libxml2

前端 未结 6 2063
孤街浪徒
孤街浪徒 2020-12-20 18:32

I am working on a parser to get data from an XML file. I am using libxml2 to extract data. I am a not able to get the attributes from nodes. I only found nb_attributes

6条回答
  •  一生所求
    2020-12-20 19:24

    I think I found why you only got 1 attribute (at least it happened to me).

    The problem was that I read attributes for first node but next is a text node. Don't know why, but node->properties gives me a reference to a non-readable part of memory, so it crashed.

    My solution was to check node type (element is 1)

    I'm using a reader, so:

    xmlTextReaderNodeType(reader)==1
    

    The entire code you can get it from http://www.xmlsoft.org/examples/reader1.c and add this

    xmlNodePtr node= xmlTextReaderCurrentNode(reader);
    if (xmlTextReaderNodeType(reader)==1 && node && node->properties) {
        xmlAttr* attribute = node->properties;
        while(attribute && attribute->name && attribute->children)
        {
          xmlChar* value = xmlNodeListGetString(node->doc, attribute->children, 1);
          printf ("Atributo %s: %s\n",attribute->name, value);
          xmlFree(value);
          attribute = attribute->next;
        }
    }
    

    to line 50.

提交回复
热议问题