how to read a part of xml file in C++ using Libxml

2019-01-20 20:43发布

问题:

Hello i need to know "how to read a part of xml file in C++ using Libxml2". In my xml file I have :

<svg>
    <g>
       <path d="11"/>
    </g>
</svg>

I want to see a value of "d" on my c++ program, when I come to this point :

   xmlNode *cur_node = NULL;

    for (cur_node = a_node; cur_node; cur_node = cur_node->next) {

      if(xmlStrEqual(xmlCharStrdup("path"),cur_node->name)){


            printf("element: %s\n", cur_node->name);
        }

        print_element_names(cur_node->children);
    }    
}

I dont know what I need to do, please help me.

回答1:

I'm not sure I understand the question, but it sounds like you want to print the attribute "d" in the element "path". In the code above, you need something like this:

xmlChar *d = xmlGetProp(cur_node, "d");
... do something ...
xmlFree(d);


回答2:

something like that ?

static void
print_element_names(xmlNode * a_node)

{

   xmlNode *cur_node = NULL;
   xmlChar        *d;

   for (cur_node = a_node; cur_node; cur_node = cur_node->next) {    

      if(xmlStrEqual(xmlCharStrdup("path"),cur_node->name)){ 
          printf("element: %s\n", cur_node->name);
      }

      print_element_names(cur_node->children);  

      if(xmlGetProp(cur_node, "d")){  

      printf("wspolrzedne: %s\n", d);
   }

   xmlFree(d);
}    


回答3:

Below function will read complete xml with node and values,

int readxml(xmlDocPtr pFilePointer,xmlNodePtr pNodePointer) {
  while (pNodePointer != NULL) {
    if ((xmlStrcmp(pNodePointer->name, (const xmlChar *)"text"))) {
      printf("%s\n", pNodePointer->name);
    } else {
    }
    if (NULL != pNodePointer->xmlChildrenNode) {
      pNodePointer = pNodePointer->xmlChildrenNode;
      if ((!xmlStrcmp(pNodePointer->name, (const xmlChar *)"text"))) {
        string node;
        xmlNodeListGetStringWrapper(pFilePointer, pNodePointer, node);
        printf("%s\n", node.c_str());
        continue;
      }
    } else if (pNodePointer->next != NULL) {
      pNodePointer = pNodePointer->next;
    } else {
      pNodePointer = pNodePointer->parent;
      pNodePointer = pNodePointer->next;
    }
  }
  return 0;
}


标签: c++ xml libxml2