解析XML文件时显示其中的一部分

And*_*y M 3 xml string qt parsing tostring

考虑以下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>
Run Code Online (Sandbox Code Playgroud)

假设我想解析这个文件并将每个配方收集为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>
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做?你们知道一个快速而干净的方法来执行此操作吗?

在此先感谢您的帮助 !

Max*_*vko 5

每个QDomNode都有

void QDomNode::save ( QTextStream & str, int indent) const
Run Code Online (Sandbox Code Playgroud)

方法和QTextStream有

QString * string () const
Run Code Online (Sandbox Code Playgroud)

所以,你只需使用这些方法,并获得简单,代码页感知和灵活的代码(QDomNode和QTextStream都是非常强大的类型).

您可以使用firstChildElement(name)/ nextSiblingElement(name)遍历具有特定名称的元素,或者您可以获取配方的根元素并编写foreach(QDomNode节点,root.childNodes())或smth.有很多方法可以在Qt中使用Xml.看看Trolls提供的教程.