我试图遍历特定 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
,虽然我个人更喜欢前者。