C++ Qt xml:更新由ID标识的属性值
我想更新以下xml文件的单个属性值:C++ Qt xml:更新由ID标识的属性值,c++,xml,qt,qt5.3,C++,Xml,Qt,Qt5.3,我想更新以下xml文件的单个属性值: <table> <obj ID="101103" name="name_a" type="nametype" cat="txt"/> <obj ID="101104" name="name_b" type="nametype" cat="txt"/> <obj ID="101105" name="name_c" type="nametype" cat="txt"/> <ob
<table>
<obj ID="101103" name="name_a" type="nametype" cat="txt"/>
<obj ID="101104" name="name_b" type="nametype" cat="txt"/>
<obj ID="101105" name="name_c" type="nametype" cat="txt"/>
<obj ID="101106" name="name_d" type="nametype" cat="txt"/>
[...]
</table>
我的问题是,如何更新此元素中的单个值。使用QDomDocument。速度较慢,但允许修改。您也可以将QStreamWriter与代码结合起来,但这要困难得多。
static void xmlActions::writeXMLValue(QString XMLID, QString attrName, QString attrVal, QFile *XMLFile, bool newID)
{
if(XMLFile->open(QIODevice::ReadOnly))
{
//comes true if the ID is found:
bool hold = false;
if (XMLFile->open(QIODevice::ReadWrite))
{
QXmlStreamReader reader(XMLFile->readAll());
while(!reader.atEnd())
{
reader.readNext();
foreach(const QXmlStreamAttribute &attr, reader.attributes())
{
if (attr.value().toString() == XMLID)
{
// the ID has been found, flag is set
hold = true;
}
if (attr.name().toString() == attrName)
{
// now we are searching for the attribute which value is to change. If it 'belongs' to the found ID (hold == true) we change it's value:
if (hold == true)
{
//do changes to the attribute value, when it's found.
//e.g. change "name_a" to "name_x"
}
}
}
//reset the flag.
hold = false;
}
}
XMLFile->close();
}
}