下面是我想要阅读的XML格式:
<base>
<pasta>name
<musica>my audio.mp3</musica>
<musica>my audio.mp3</musica>
<musica>my audio.mp3</musica>
<musica>my audio.mp3</musica>
</pasta>
<pasta>name2
<musica>my audio.mp3</musica>
<musica>my audio.mp3</musica>
</pasta>
</base>
我用来读取xml的代码:
QList<PastaBase>* BaseWrapper::carregarDeXml(QString caminhoArquivoXml)
{
//Carrega do XML
QFile arquivoXml(caminhoArquivoXml);
if(!arquivoXml.open(QIODevice::ReadOnly))
{
QString s(QString::fromUtf8("Erro ao abrir arquivo de base"));
QMessageBox::warning(0, "Erro", s);
throw QString("Erro ao abrir arquivo de base");
}
QList<PastaBase> *base = new QList<PastaBase>();
QXmlStreamReader r;
r.setDevice(&arquivoXml);
while(!r.atEnd() && !r.hasError())
{
r.readNext();
if(r.isStartElement())
{
if(r.name().toString() == QString("pasta"))
{
PastaBase p;
p.setNome(r.readElementText());
r.readNextStartElement();
while(r.name().toString() == QString("musica"))
{
std::cout << "elemento: " << r.name().toLatin1().constData() << " - valor: " << r.readElementText().toLatin1().constData() << std::endl;
p.getMidias()->append(r.readElementText());
r.readNextStartElement();
}
base->append(p);
}
}
}
arquivoXml.close();
return base;
}
输出 - 卡在while循环中:
elemento: musica - valor:
elemento: musica - valor:
elemento: musica - valor:
elemento: musica - valor:
elemento: musica - valor:
elemento: musica - valor:
elemento: musica - valor:
elemento: musica - valor:
...
...
...
答案 0 :(得分:0)
您确定这是您正在运行的代码吗?我试图复制/粘贴它,但它不能编译......
r.name()
返回QStringRef,其中没有toLatin1()
方法。如果我用toString()
方法替换它,那么它对我编译很好。
但你的问题不存在,我认为你在xml文件中所做的是非法的:
<pasta>you can't put something here
<musica>my audio.mp3</musica>
<musica>my audio.mp3</musica>
<musica>my audio.mp3</musica>
<musica>my audio.mp3</musica>
</pasta>
导致无限循环的行是p.setNome(r.readElementText());
,因为如果你有子标签,你不能在这里输入文字。
我对XML不是很熟悉,但我认为你的问题就在这里。有人可以确认一下吗?