如何在C ++中将格式化文本转换为XML

时间:2011-07-21 05:30:35

标签: c++ xml

我已经阅读了一个文本文件,现在我们需要将收到的输入转换为XML数据。

例如:阅读文本文件产生:

English        100
Science         80
Computers       77

现在我们需要输出:

<head>
    <English>100</English>
    <Science>80</Science>
    <Computers>77</Computers>
</head>

我们如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

您可以做的是,在阅读文本文件后,将<>添加到主题中。

如果fout是输出std::filestream,则subjectstd::string,并且 scoreintunsigned

fout << "<head>" << std::endl;    
while (/* file is not finished */)
{
    // Read a string and an int from the file

    subject.insert(0,"<");
    subject.insert(subject.size(),">");
    fout << subject << score;

    subject.insert(1,"/");
    fout << subject<< std::endl;
}

fout << "</head>" << std::endl;

答案 1 :(得分:0)

使用TinyXML: Here

你需要的所有东西,只有4个源文件 - 也是简单的东西:

void build_simple_doc( )
{
    // Make xml: <?xml ..><Hello>World</Hello>
    // Warning - this code isn't exception safe!
    TiXmlDocument doc;
    TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" );
    TiXmlElement * element = new TiXmlElement( "Hello" );
    TiXmlText * text = new TiXmlText( "World" );
    element->LinkEndChild( text );
    doc.LinkEndChild( decl );
    doc.LinkEndChild( element );
    doc.SaveFile( "madeByHand.xml" );

    delete decl;
    delete element;
    delete text;
}

创建

<?xml version="1.0" ?>
<Hello>World</Hello>