c++ - QDomDocument - 如何从 QString 创建?

标签 c++ xml qt

如何从QString创建QDomDocument,其中包含很多XML节点?

我知道一种方法 - setContent 方法。但这不是更好的方法 - 如果我需要从内容类似于

的字符串创建 XML
<food>
    <name>Strawberry Belgian Waffles</name>
    <price>$7.95</price>
    <description>Light Belgian waffles covered with strawberries and whipped cream</description>
    <calories>900</calories>
</food>
<food>
    <name>Berry-Berry Belgian Waffles</name>
    <price>$8.95</price>
    <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
    <calories>900</calories>
</food>
<food>
    <name>Homestyle Breakfast</name>
    <price>$6.95</price>
    <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
    <calories>950</calories>
</food>

我需要像这样传递给 setContent 字符串

    rhythmdb.setContent("<?xml version='1.0' encoding='UTF-8'?>"
                       " <breakfast_menu>"+res+"</breakfast_menu");

这不是好方法 - 从 setContent 指定 xml 版本和编码。 正如我想象的那样,一个正确的决定:

  1. 我需要创建QDomDocument rhythmdb;

  2. 为 rhythmdb 指定 XML 版本和编码

  3. 创建子元素,例如 QDomElement childElement= rhythmdb.createElement("breakfast_menu");

  4. 附加 XML breakfast_menu 元素的内容,如 childElement.setContent(res);

但是 QDomElement 对象没有 setContent 方法。

我怎样才能用这种方式编程?

谢谢。

最佳答案

查看文档,您似乎确实只能将 QString 转换为整个 QDomDocument。您不能将其作为 QDomNode(s) 加载到现有节点中。

您可以——但是——使用QDomDocument::importNode() 在QDomDocuments 之间复制加载的节点。 .因此,为了混合来自不同来源 QString 的 Material ,您可以 setContent()在临时文档上,然后将其所需的任何节点导入到目标文档中。导入后,将这些本地拷贝插入到您想要的位置。

在您的情况下,这不会帮助您使用当前形式的字符串。它是一系列没有单一根元素的 sibling 。而 QDomDocument 只需要一个 setContent()来自有效的 XML,根据 Wikipedia :

Each XML document has exactly one single root element. It encloses all the other elements and is therefore the sole parent element to all the other elements. ROOT elements are also called PARENT elements.

因此如果setContent()是您唯一的字符串到 XML 机制,您需要在加载之前将其包装在单个父项中。在它前面加上 <breakfast_menu>并附加 </breakfast_menu>通过适当的 ROOT 使其成形似乎很好。

但是不用担心 <?xml version='1.0' encoding='UTF-8'?> :

  • 输入时的编码仅在从字节流加载时相关。您正在从 QString 加载,解码已经完成......(正确或不正确)。这是Unicode code points到那时,无论你说什么,编码都会产生零影响。

  • 如果您想要在您的输出 上声明 XML,无论如何您都必须在 Qt 中手动添加它。默认情况下不包含它,必须使用 QDomDocument::createProcessingInstruction 明确指定.这部分是因为规范说它是可选的,部分是因为无论如何永远不会有另一个 XML 标准。 ;-)

关于c++ - QDomDocument - 如何从 QString 创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29195697/

相关文章:

java - 指定 DocumentBuilders 使用 DTD 进行 XML 解析?

php - 如何在对 XPLAN API 的 CURL 请求中构造 edai.Search 方法的第三个参数?

c++ - 发射信号不正常

c++ - 从 ID3DBLob 填充 std::vector<byte>

c++ tga 解析 incorrect_color/distortion with some resolutions

c++ - 使用线程在以元音或辅音开头的单词之间交替

c# - 二进制搜索算法的扩展,用于查找要在数组中搜索的键值的第一个和最后一个索引

xml - XML和线程

linux - atof 在 QApplication 之后截断小数部分

c++ - 不能将标准 C++ 库包含在 MinGW 中