21xrx.com
2024-11-22 03:49:09 Friday
登录
文章检索 我的文章 写文章
C++解析XML文件的方法
2023-07-04 17:54:31 深夜i     --     --
C++ 解析 XML文件 方法

XML(可扩展标记语言)是一种常用的文件格式,用于在应用程序之间传递和存储数据。在C++编程中,解析XML文件是一项基本任务,因此本文将介绍如何使用C++解析XML文件的方法。

1.使用第三方库

C++提供了几个第三方库来解析XML文件,如TinyXML、Xerces-C++、RapidXML等等。其中,TinyXML是一个易于学习和使用的开源库,允许用户在几行代码中解析和读取XML文件。以下是使用TinyXML解析XML文件的样例代码:


#include "tinyxml2.h"

#include <iostream>

using namespace std;

using namespace tinyxml2;

int main() {

  XMLDocument doc;

  doc.LoadFile("example.xml");

  XMLElement* root = doc.FirstChildElement("students");

  for (XMLElement* e = root->FirstChildElement("student"); e != NULL; e = e->NextSiblingElement("student")) {

    const char* id = e->Attribute("id");

    cout << "Student id: " << id << endl;

    XMLElement* name = e->FirstChildElement("name");

    cout << "Name: " << name->GetText() << endl;

    XMLElement* grade = e->FirstChildElement("grade");

    cout << "Grade: " << grade->GetText() << endl;

  }

  return 0;

}

2.使用C++标准库

C++标准库也包含解析XML文件的功能。用户可以使用标准库提供的SAX或DOM解析器以及XMLReader工具来解析XML文件。以下是使用C++标准库解析XML文件的样例代码:


#include <iostream>

#include <fstream>

#include <sstream>

#include <string>

#include <vector>

#include <algorithm>

#include <stdexcept>

#include <locale>

#include <codecvt>

#include <iostream>

#include <iomanip>

#include <regex>

#include <xercesc/util/XMLString.hpp>

#include <xercesc/sax2/XMLReaderFactory.hpp>

#include <xercesc/sax2/DefaultHandler.hpp>

using namespace std;

using namespace xercesc;

class MySAXHandler : public DefaultHandler {

public:

  void startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const Attributes& attrs) {

    if (XMLString::compareString(localname, XMLString::transcode("student")) == 0) {

      cout << "Student: " << endl;

      for (int i = 0; i < attrs.getLength(); i++) {

        XMLCh* attrLocalName = attrs.getLocalName(i);

        XMLCh* attrValue = attrs.getValue(i);

        cout << "  " << XMLString::transcode(attrLocalName) << ": " << XMLString::transcode(attrValue) << endl;

      }

    }

    else if (XMLString::compareString(localname, XMLString::transcode("name")) == 0)

      cout << "Name: ";

      insideText = true;

    

    else if (XMLString::compareString(localname, XMLString::transcode("grade")) == 0)

      cout << "Grade: ";

      insideText = true;

    

  }

  void endElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname) {

    if (XMLString::compareString(localname, XMLString::transcode("name")) == 0 ||

      XMLString::compareString(localname, XMLString::transcode("grade")) == 0)

      cout << endl;

      insideText = false;

    

  }

  void characters(const XMLCh* const chars, const XMLSize_t length) {

    if (insideText) {

      wchar_t* wchars = XMLString::transcode(chars);

      wstring str(wchars);

      wcout << str;

      XMLString::release(&wchars);

    }

  }

private:

  bool insideText = false;

};

int main(int argc, char* argv[]) {

  if (argc != 2) {

    cerr << "Usage: " << argv[0] << " XMLFileName" << endl;

    return 1;

  }

  try {

    XMLPlatformUtils::Initialize();

    auto parser = XMLReaderFactory::createXMLReader();

    auto handler = make_shared<MySAXHandler>();

    parser->setContentHandler(handler.get());

    parser->setErrorHandler(handler.get());

    parser->parse(argv[1]);

  }

  catch (...)

    cerr << "Exception occurred" << endl;

  

  XMLPlatformUtils::Terminate();

  return 0;

}

总之,在C++中解析XML文件是一种非常普遍的任务,而使用TinyXML或Xerces-C++等库可以使此过程变得简单且易于理解。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复