代码之家  ›  专栏  ›  技术社区  ›  Andy M

分析XML文件时显示该文件的一部分

  •  3
  • Andy M  · 技术社区  · 15 年前

    请考虑以下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>
    

    我怎么能这样做?你们知道一个快速干净的方法来完成这个任务吗?

    提前谢谢你的帮助!

    2 回复  |  直到 15 年前
        1
  •  5
  •   Maxim Popravko    15 年前

    每个qdomnode都有

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

    方法,而qtextstream具有

    QString * string () const
    

    所以,您只需使用这些方法,就可以获得简单、代码页覆盖且灵活的代码(qdomnode和qtextstream都是非常强大的类型)。

    可以使用firstChildElement(name)/nextSiblingElement(name)遍历具有特定名称的元素,也可以获取配方的根元素并写入foreach(qdomnode node,root.childnodes())或smth。在qt中处理xml有很多方法。看看提供的教程巨魔。

        2
  •  0
  •   dawg    15 年前

    qt同时支持sax和dom。只需写一个查询。 Here is a tutorial.