从C++程序创建XML文件

mad*_*ina 7 c++

我有这个变量,一个双指针向量,如:

vector<double*> myIntersections;
Run Code Online (Sandbox Code Playgroud)

其中包含一个向量,其元素都是双精度的二维向量.我想创建一个XML文件(例如调用myfile.axl - 具有这个特定的扩展名),其中文件的每一行都由向量的每个元素给出(因此在每一行上,一个元素至少需要向量[i] ] [0],vector [i] [1])和XML文件的标签是..等(因此用户定义).XML应该是这样的文件:

<point name="intersectPoints" size="4" color="rgb">
  -2.68 1.82 0.0 255 0 0
  -2.63 1.03 0.0 255 0 0
</point>
Run Code Online (Sandbox Code Playgroud)

其中vector [0] [0] = - 2.68,vector [0] [1] = 1.82等等(0.0 255 0 0总是一样)我知道如何用C++编写文件(我正在考虑使用fstream库),但我不知道如何创建XML标签(除了字符串以这种方式,他们将通过字符串)所以我有点迷失.

任何建议都受到欢迎.谢谢你的时间,马达利娜

Myk*_*yev 7

请.请不要自己创建XML.

使用将生成有效且正确的XML文件的库.
同样的事情与阅读XML有关.你不打算用ifstream阅读XML,是吗?因此,如果你有XML库来读取XML文件,我很确定这个库允许创建XML.

以下是tinyxml的示例代码

int main()
{
    VertexList vl;

    vl.push_back( Vertex( Point3d( -2.68, 1.82, 0.0 ), RGB( 255, 0, 0 )));
    vl.push_back( Vertex( Point3d( -2.63, 1.03, 0.0 ), RGB( 255, 0, 0 )));

    std::ostringstream ss;
    std::for_each( vl.begin(), vl.end(), VertexPrint( ss ) );

    // write xml
    TiXmlDocument doc;
    TiXmlDeclaration decl( "1.0", "", "" );  
    doc.InsertEndChild( decl );  

    TiXmlElement point( "point" );  

    TiXmlComment comment( "My Points" );
    point.InsertEndChild( comment );  

    point.SetAttribute("name", "intersectPoints");
    point.SetAttribute("size", vl.size());
    point.SetAttribute("color", "rgb");

    TiXmlText values( ss.str() );
    point.InsertEndChild( values );  

    doc.InsertEndChild( point );  
    doc.SaveFile( "out.xml" );  
}
Run Code Online (Sandbox Code Playgroud)

哪里 Vertex

struct Point3d
{
    Point3d( double x, double y, double z ):
        x_(x), y_(y), z_(z)
    {}
    double x_;
    double y_;
    double z_;
};
struct RGB
{
    RGB( int r, int g, int b ):
        r_(r), g_(g), b_(b)
    {}
    int r_;
    int g_;
    int b_;
};
struct Vertex
{
    Vertex( const Point3d& coord, const RGB& color ):
        coord_( coord ), color_( color )
    {}
    Point3d coord_;
    RGB color_;
};
typedef std::vector< Vertex > VertexList;
Run Code Online (Sandbox Code Playgroud)

并且VertexPrint

struct VertexPrint
{
    VertexPrint( std::ostringstream& result ):
        result_( result )
    {}
    void operator() ( const Vertex& v )
    {
        result_ << v.coord_.x_ <<" "<< v.coord_.y_ <<" "<< v.coord_.z_ <<" "
                << v.color_.r_ <<" "<< v.color_.b_ <<" "<< v.color_.b_ <<";";
    }
    std::ostringstream& result_;
};
Run Code Online (Sandbox Code Playgroud)

您还可以考虑提升XML序列化


Zac*_*man 5

查看TinyXml.它非常轻巧.从文档:

TinyXML使用文档对象模型(DOM),这意味着XML数据被解析为可以浏览和操作的C++对象,然后写入磁盘或其他输出流.您还可以从头开始使用C++对象构造XML文档,并将其写入磁盘或其他输出流.

我在自己的项目中使用了TinyXml,使用起来很愉快.

编辑:除了TinyXML之外,我还使用ticpp(TinyXml ++),它在库的顶部引入了更多的C++特性(异常,模板,迭代器等).


Max*_*Max 0

假设您在 Windows 上并使用 Visual Studio,则可以使用MSXML或其他第 3 方库。