【问题标题】:Display part of an XML file while parsing it在解析 XML 文件时显示它的一部分
【发布时间】:2010-04-12 12:05:13
【问题描述】:

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

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

提前感谢您的帮助!

【问题讨论】:

    标签: xml string qt parsing tostring


    【解决方案1】:

    每个 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。查看 Trolls 提供的教程。

    【讨论】:

    • 您好,非常感谢您的回答!我明天试试!我会及时通知你我的进展!
    • ok :) 你最好也看看样品,它相当简单干净。
    • 嘿,我再说一遍,非常感谢队友,它工作得很好!这正是我所需要的......
    【解决方案2】:

    Qt 支持 SAX 和 DOM。只写一个查询。 Here is a tutorial.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-19
      • 2013-06-08
      • 2022-11-28
      • 1970-01-01
      • 2022-10-03
      • 2011-05-30
      • 1970-01-01
      • 2011-07-09
      相关资源
      最近更新 更多