简体   繁体   English

如何使用Libxml2在C++中读取xml文件的一部分

[英]how to read a part of xml file in C++ using Libxml2

Hello i need to know "how to read a part of xml file in C++ using Libxml2".您好,我需要知道“如何使用 Libxml2 在 C++ 中读取 xml 文件的一部分”。 In my xml file I have :在我的 xml 文件中,我有:

<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 :我想在我的 c++ 程序中看到“d”的值,当我来到这一点时:

   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.我不知道我需要做什么,请帮助我。

I'm not sure I understand the question, but it sounds like you want to print the attribute "d" in the element "path".我不确定我是否理解这个问题,但听起来您想在元素“path”中打印属性“d”。 In the code above, you need something like this:在上面的代码中,你需要这样的东西:

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

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

Below function will read complete xml with node and values,下面的函数将读取带有节点和值的完整 xml,

xmlDocPtr pFilePointer = xmlParseFile(xmlFile);
xmlNodePtr pNodePointer = xmlDocGetRootElement(pFilePointer);

void readXML(const xmlDocPtr cpFilePointer, const xmlNodePtr cpNodePointer) {
    string value;
    xmlDocPtr pFilePointer = cpFilePointer;
    xmlNodePtr pNodePointer = cpNodePointer;
    while (pNodePointer != NULL) {
        if (NULL != pNodePointer->xmlChildrenNode) {
            xmlNodePtr pParentPointer = pNodePointer;
            string node = (const char *)pParentPointer->name;
            pNodePointer = pNodePointer->xmlChildrenNode;
            if (!xmlStrcmp(pNodePointer->name, (const xmlChar *)"text")) {
                xmlNodeListGetStringWrapper(pFilePointer, pNodePointer, value);
                cout << node << ":" << value << endl;
            } else {
                LOG2((TEXT("no need to read node %s\n"), pParentPointer->name));
            }
        } else if (NULL != pNodePointer->next) {
            pNodePointer = pNodePointer->next;
        } else {
            pNodePointer = pNodePointer->parent;
            pNodePointer = pNodePointer->next;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM