0

我试图遍历特定 XML 节点的所有子节点并加入它们的name属性。结构:

<params>
    <param name="BLAH" />
</params>

期望的结果:

PARAM1='$PARAM1',PARAM2='$PARAM2',PARAM3='$PARAM3'[...]

编码:

    // Create empty text stream
    QTextStream paramNames("");
    // Start looping child by child
    QDomElement child = params.firstChildElement();
    bool firstIteration = true;
    while( !child.isNull() ) {  
        QString param_name = child.attribute("n");
        // Skips empty names
        if(param_name.length()>0) {
          // This prevents both leading and trailing comma
          if(!firstIteration)
              paramNames<<",";
          else
              firstIteration = false;
          // This should fill in one entry
          paramNames<<param_name<<"='$"<<param_name<<'\'';
        }
        child = child.nextSiblingElement();
    }

现在连调试器都说如果我这样做

QString paramNamesSTR = paramNames.readAll();

paramNamesSTR是一个空字符串。但是,如果我改用std库,则一切正常:

    std::stringstream paramNames("");
    QDomElement child = params.firstChildElement();
    bool firstIteration = true;
    while( !child.isNull() ) {  
        std::string param_name = child.attribute("n").toUtf8().constData();
        if(param_name.length()>0) {
          if(!firstIteration)
              paramNames<<",";
          else
              firstIteration = false;
          paramNames<<param_name<<"='$"<<param_name<<'\'';
        }
        child = child.nextSiblingElement();
    }
    QString paramNamesSTR = QString::fromStdString( paramNames.str() );

那么有什么区别呢?为什么 QtQTextStream返回空字符串?我真的更喜欢与使用过的库保持一致,因此使用QTextStream而不是std::stringstream,虽然我个人更喜欢前者。

4

1 回答 1

3

为了能够使用QTextStream,你需要传递一些东西来操作(流本身不存储任何数据,它只是在字符串或 iodevice 上操作)。将字符串文字传递给它不是正确的做法。不同之处在于,当您创建std::stringstream并传递一个字符串文字时,会自动创建一个底层流缓冲区,并且该文字用作缓冲区的初始值。在 的情况下QTextStream,它创建了一个包含传递的文字的只读流。创建 a 的正确方法QTextStream是先创建缓冲区,然后创建流以对该缓冲区进行操作,例如:

QString string; //you can also use a QByteArray, or any QIODevice
QTextStream stream(&string);
于 2015-10-05T11:28:11.780 回答