2010-04-12 27 views
3

考慮下面的XML文件:顯示部分,而解析它

<cookbook> 
<recipe xml:id="MushroomSoup"> 
    <title>Quick and Easy Mushroom Soup</title> 
    <ingredient name="Fresh mushrooms" 
       quantity="7" 
       unit="pieces"/> 
    <ingredient name="Garlic" 
       quantity="1" 
       unit="cloves"/> 
</recipe> 
<recipe xml:id="AnotherRecipe"> 
    <title>XXXXXXX</title> 
    <ingredient name="Tomatoes" 
       quantity="8" 
       unit="pieces"/> 
    <ingredient name="PineApples" 
       quantity="2" 
       unit="cloves"/> 
</recipe> 
</cookbook> 

比方說,我要分析此文件,並收集每個配方爲XML,每一個作爲一個分離的QString。

例如,我想有一個包含的QString:

<recipe xml:id="MushroomSoup"> 
    <title>Quick and Easy Mushroom Soup</title> 
    <ingredient name="Fresh mushrooms" 
       quantity="7" 
       unit="pieces"/> 
    <ingredient name="Garlic" 
       quantity="1" 
       unit="cloves"/> 
</recipe> 

我怎麼能這樣做呢?你們知道一個快速而乾淨的方法來執行此操作嗎?

在此先感謝您的幫助!

回答

5

每個QDomNode有

void QDomNode::save (QTextStream & str, int indent) const 

方法,以及QTextStream有

QString * string() const 

所以,你只需要使用這些方法,並獲得簡單,代碼頁,awared和靈活的代碼(包括QDomNode和QTextStream是非常強大的類型)。

您可以通過使用firstChildElement(name)/ nextSiblingElement(name)來遍歷具有特定名稱的元素,或者您可以獲取配方的根元素並編寫foreach(QDomNode節點,root.childNodes())或者smth 。有很多方法可以讓Qt中的Xml進程。看看Trolls提供的教程。

+0

嘿,非常感謝您的回答!我明天會試一試!我會隨時更新我的​​進度! – 2010-04-12 21:14:43

+1

ok :)你最好還是檢查一下樣品,它很簡單,很乾淨。 – 2010-04-12 21:35:12

+0

嘿,所以我再重複一次,非常感謝你的配偶,它的工作非常好!它完全是我需要的...... – 2010-04-13 06:00:15