2011-07-21 98 views
-6

我已經讀入了一個文本文件,現在我們需要將接收到的輸入轉換爲XML數據。如何將格式化文本轉換爲C++中的XML

例如爲:讀取文本文件的產量:

English  100 
Science   80 
Computers  77 

現在我們需要輸出爲:

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

我們怎樣才能做到這一點?

+0

這是家庭作業? – Soren

+0

-1:「沒有顯示任何研究成果」 –

+0

XSLT可能更適合這項任務。 –

回答

2

您可以做的是,在閱讀文本文件後,將<>附加到主題。

如果fout是輸出std::filestreamsubjectstd::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; 
+0

我只是寫第一行,但後來我認爲我的回答是不完整的。 – xeon111

+0

清理這個,所以它會+1值得。 – user7116

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> 
+0

-1:您演示泄漏代碼。不要忘記,有多少潛水員在這裏沒有經歷過看到這些泄漏,並把你的代碼改正。 –

+0

@phresnel - 你是對的 - 我剛剛從教程頁面獲得了代碼。無論如何,它現在是固定的。雖然不是例外。 '潛伏者'可能不知道如何使用auto_ptrs。 – Schnommus

+5

壞代碼互聯網傳播的有趣演示。 --1。 –

相關問題