WindowsでC++からlibxml2を使う

Posted on 5月 22, 2008
Filed Under libxml2, C++, windows |

環境は
VisualC++2005ExpressEdition

http://www.zlatkovic.com/pub/libxml/
こちらからWindows用バイナリをDL
今のバージョンは libxml2-2.6.32+.win32.zip

C/C++ 追加のインクルードディレクトリに libxml2/include を追加
リンカ 追加のライブラリディレクトリに libxml2/lib を追加

こんなRSSを

XML:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <rss version="2.0">
  3.   <channel>
  4.     <copyright>Copyright 2007-2008, ...</copyright>
  5. snip..

こんな感じでパースできる

C++:
  1. #include <libxml /xmlmemory.h>
  2. #include </libxml><libxml /parser.h>
  3.  
  4. int XMLParser::parse( string filename ) {
  5.  
  6.     xmlDocPtr doc = xmlParseFile( filename.c_str() );
  7.     if (doc == NULL ) {
  8.         fprintf(stderr,"Document not parsed successfully. \n");
  9.         return 0;
  10.     }
  11.  
  12.     xmlNodePtr cur = xmlDocGetRootElement(doc);
  13.     if (cur == NULL) {
  14.         fprintf(stderr,"empty document\n");
  15.         xmlFreeDoc(doc);
  16.         return 0;
  17.     }
  18.    
  19.     if (xmlStrcmp(cur->name, (const xmlChar *) "rss")) {
  20.         fprintf(stderr,"document of the wrong type, root node != rss");
  21.         xmlFreeDoc(doc);
  22.         return 0;
  23.     }
  24.  
  25.     xmlChar *version = xmlGetProp(cur, (const xmlChar *)"version");
  26.     printf("version: %s\n", version);   // "2.0"
  27.     xmlFree(version);
  28.    
  29.     xmlFreeDoc(doc);
  30.     return 1;
  31. }

めんどくさい

Comments

Leave a Reply