QDomDocument到QDomElement转换

时间:2014-02-13 19:57:20

标签: qt xmpp

我有从QByteArray加载到QDomDocument的xmpp iq,但我需要它作为QDomElement

<iq from='users.netlab.cz' to='test_soc@jabbim.sk/QXmpp' id='search0' type='result'>
  <query xmlns='jabber:iq:search'>
    <instructions>You need an x:data capable client to search</instructions>
    <x xmlns='jabber:x:data' type='form'>
      <title>Search users in users.netlab.cz</title>
      <instructions>blahblah</instructions>
      <field type='text-single' label='User' var='user'/>
      ... 
      <field type='text-single' label='Organization Unit' var='orgunit'/>
    </x>
  </query>
</iq>

所以我刚用

QDomElement element = doc.toElement();

但它没有返回任何数据,我对xml并不熟悉所以我不确定这是否正确。任何人都可以告诉我如何将此文档转换为元素,或者它是否能够以某种方式直接将数据从QByteArray加载到QDomElement?

1 个答案:

答案 0 :(得分:5)

As mentioned in the comments,使用QDomNode::toElement()不起作用,因为文档本身在技术上不是一个元素。使用QDomDocument::documentElement()来获取根元素。

The QDomDocument documentation包含以下使用示例:

// print out the element names of all elements that are direct children
// of the outermost element.
QDomElement docElem = doc.documentElement();

QDomNode n = docElem.firstChild();
while(!n.isNull()) {
    QDomElement e = n.toElement(); // try to convert the node to an element.
    if(!e.isNull()) {
        cout << qPrintable(e.tagName()) << endl; // the node really is an element.
    }
    n = n.nextSibling();
}