我想更新以下 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"/>
<obj ID="101106" name="name_d" type="nametype" cat="txt"/>
[...]
</table>
该代码通过“ID”值标识要更新的属性。ID 在前,属性(例如“名称”)紧随其后。
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();
}
}
我的问题是,如何更新此元素中的单个值。