C + + uses Xerces to read XML

Source: Internet
Author: User
Tags xml parser

XML as an important file format, the application surface is very wide. From the Web. config, to the Android page design development, WebService communication and so on. Sometimes you need us through the process of creating and parsing, recently completed a C + + project, you need to read the XML configuration file, about the choice of XML parser, you can refer to: http://www.metsky.com/archives/578.html.

Personally prefer Apache's Open source project, so use: Xerces. Its use, in fact, the official has a lot of demo, see: Http://xerces.apache.org/xerces-c/samples-3.html. Personally feel domcount more practical, below to share my personal practice. Reads the attributes and literal values of the specified node in the XML in the DOM mode.

Development environment: Visual Studio 2013

Download the source code will not say, address: http://apache.dataguru.cn//xerces/c/3/sources/xerces-c-3.1.2.zip, can not download, to http://xerces.apache.org/ xerces-c/download.cgi download.

First of all, compile Xerceslib project, get xerces-c_3_1d.dll,xerces-c_3d.lib two files, next need to add these 2 files in the target project, as well as the corresponding header files, then a bit of configuration, followed by coding.

Detailed steps below:

1. VS 2013 Open Xerces-c-3.1.2\projects\win32\vc12\xerces-all\xerces-all.sln

Check xerceslib-> right-click Compile

2. Copy the Xerces-c_3_1d.dll,xerces-c_3d.lib file under the Xerces-c-3.1.2\build\win32\vc12\debug folder to the target project's compiled output directory (once compiled), such as: ~\ Debug\ below.

3. Copy the SRC folder under xerces-c-3.1.2 to the target project.

4. Configuration include directories increased. \SRC,

Configuration dependencies Increase Xerces-c_3d.lib,library directories add $ (OutDir) (that is, compile output directory)

The 2-4-step is a common configuration method for all calls to the dynamic library, which can be flexibly configured if the principle is understood.
The contents of the XML file are as follows:

<?xml version="1.0"encoding="UTF-8"?><config> <child> <node1> <list name="1">test11</list> <list name="2">test12</list> </node1> <node2> <list name="1">test21</list> <list name="2">test31</list> </node2> <node3> <list name="1">test31</list> <list name="2">test32</list> </node3> </child></config>

5. Begin implementing the encoding.

5.1 Include header file

1 #include <xercesc/util/PlatformUtils.hpp>2 #include <xercesc/dom/DOM.hpp>3 #include <xercesc/sax/HandlerBase.hpp>4 #include <xercesc/parsers/XercesDOMParser.hpp>

5.2 Initializing the environment

1 Try {2 xmlplatformutils::initialize ();3     }4     Catch(Constxmlexception&Tocatch) {5         //Do your failure processing here6         return;7     }8     ///9Xercesdomparser *parser =NewXercesdomparser ();TenParser->Setvalidationscheme (xercesdomparser::val_always); OneParser->setdonamespaces (true);//Optional A  -errorhandler* ErrHandler = (errorhandler*)Newhandlerbase (); -Parser->seterrorhandler (ErrHandler);

5.3 Loading an XML file

1 Try {2Parser->Parse ("D:\RUN. XML ");3     }4     Catch(Constxmlexception&Tocatch) {5         Char* Message =Xmlstring::transcode (Tocatch.getmessage ());6cout <<"Exception message is: \ n"7<< message <<"\ n";8Xmlstring::release (&message);9         return;Ten     } One     Catch(Constdomexception&Tocatch) { A         Char* Message =Xmlstring::transcode (tocatch.msg); -cout <<"Exception message is: \ n" -<< message <<"\ n"; theXmlstring::release (&message); -         return; -     } -     Catch (...) { +cout <<"unexpected Exception \ n"; -         return; +}

5.4 Start parsing

1 DOMDocument *doc = parser->getdocument (); 2 domelement *root = Doc->getdocumentelement (); // Read root node

5.5 Finding the corresponding node values and attributes

1Domnode *dn=Root;2DN = Findchildnode (DN," Child");//Finding child nodes3  for(DN = Dn->getfirstchild (); DN! =0;D n = dn->getnextsibling ())4{//traversing node1,2,3 child nodes5         if(Dn->getnodetype () = = Domnode::element_node)//this is necessary because if the type is not judged, actually each node will have a text_node, and is the first node6         {7             if(Xmlstring::comparestring (Xmlstring::transcode (Findchildnode (DN,"List")->getattributes ()->getnameditem (Xmlstring::transcode ("name"))->getnodevalue ()), Xmlstring::transcode ("1")) ==0)8{//Find the node for <list name= "1" >9cout << "Corresponding node value is:" << xmlstring::transcode (Findchildnode (DN,"List")->gettextcontent ()) <<Endl;Ten                     //Do IT CODE One ... .. A                  -             }; -              the         } -      } -Xmlplatformutils::terminate ();//Releasing the Environment

The following is the code for the Findchildnode function

1domnode* Findchildnode (Domnode *n,Char*nodename)2{//looking for nodes with the N node named NodeName3      Try4      {5           for(Domnode *child = N->getfirstchild (); Child! =0; Child = child->getnextsibling ())6          {7              if(Child->getnodetype () = = Domnode::element_node && xmlstring::comparestring (Child->getnodename (), Xmlstring::transcode (nodename)) = =0)8              {9                  returnChild ;Ten              } One          } A      } -      Catch(Constxmlexception&Tocatch) -      { the          Char* Message =Xmlstring::transcode (Tocatch.getmessage ()); -cout <<"Exception message is: \ n" -<< message <<"\ n"; -Xmlstring::release (&message); +      } -      return 0; +}

5.6 Remember to release the environment

Xmlplatformutils::terminate ();

1. The output result is

The corresponding node value is: test11

Summarize:

There are two modes of reading XML, one is event-based sax, one is DOM, this article uses DOM, in fact, getElementById () in JS is somewhat similar. The code body is complete and hopefully does not affect understanding. If you need source code, can add QQ or: 304772487 or letter: [email protected]

C + + uses Xerces to read XML

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.