如何使用 qt 删除嵌套的 xml 元素

How to delete nested xml element using qt

本文关键字:xml 元素 嵌套 删除 何使用 qt      更新时间:2023-10-16

我有这样的XML文件

<root>
   <element>
       <child id = "0"> Some Text </child> <-- Target To Delete
   </element>
   <element>
       <child id = "1"> Some Text </child>
   </element>
</root>

如何使用Qt库删除ID "0"的子元素。

QDomDocument doc;
doc.setContent(oldXml);
QDomNodeList nodes = doc.elementsByTagName("element");
for (int i = 0; i < nodes.count(); ++i)
{
    QDomNode node = nodes.at(i);
    QDomElement child = node.firstChildElement("child");
    if (!child.isNull() && child.attribute("id") == "0")
    {
        node.removeChild(child);
    }
}
QString newXml = doc.toString();