0

我用 C++(GNU 编译器)创建了一个包含 100,000 条员工记录的二进制文件。现在我需要使用 c++ 创建包含 100,000 条员工记录的 XML 表。但我不知道如何使用 C++ 代码创建 XML 表。是否有任何示例代码或教程可用于执行此程序?

4

2 回答 2

0

这是简单的人为示例

#include <iostream>
#include <vector>
#include <string>

class Employee
{
   public:
      Employee(const std::string &firstname, const std::string &lastname, int salary)
         :firstname_(firstname), lastname_(lastname), salary_(salary)
      {
      }
      friend std::ostream &operator<<(std::ostream &os, const Employee &rhs)
      {
         rhs.print(os);
         return os;
      }
   private:
      void print(std::ostream &os) const
      {
         os << "<employee>";
         os << "<firstname>" << firstname_ << "</firstname>";
         os << "<lastname>" << lastname_ << "</lastname>";
         os << "<salary>" << salary_ << "</salary>";
         os << "</employee>\n";
      }
      std::string firstname_;
      std::string lastname_;
      int salary_;
};

int main(int argc, char *argv[])
{
   std::vector<Employee> staff;

   staff.push_back(Employee("Peter", "Griffin", 10000));
   staff.push_back(Employee("Lois", "Griffin", 20000));
   staff.push_back(Employee("Chris", "Griffin", 30000));
   staff.push_back(Employee("Meg", "Griffin", 40000));
   staff.push_back(Employee("Stewie", "Griffin", 50000));
   staff.push_back(Employee("Brian", "Griffin", 60000));

   std::cout << "<staff>\n";
   for(std::vector<Employee>::const_iterator i=staff.begin(),end=staff.end(); i!=end; ++i)
   {
      std::cout << (*i);
   }
   std::cout << "</staff>\n";

   return 0;
}
于 2012-06-23T05:55:26.223 回答
0

我建议使用 XML 序列化库将数据写入自定义 XML 格式。

例如,MIT 许可的开源 C++ 库libstudxml既提供了低级 API

void start_element (const std::string& name);
void end_element ();
void start_attribute (const std::string& name);
void end_attribute ();
void characters (const std::string& value);

和高级 API

template <typename T>
  void element (const T& value);
template <typename T>
  void characters (const T& value);
template <typename T>
  void attribute (const std::string& name,
      const T& value);

libstudxml文档提到它的序列化源代码起源于一个用于 XML 序列化的小型 C 库,称为Genx(也是 MIT 许可的)。

于 2015-07-17T15:28:50.360 回答