我需要使用QDomDocument从XML文件中删除嵌套的多级(未知深度)标记。这样做的正确方法是什么? 以下是XML文件的示例
<A>
<B>
<C>
.............................
</C>
</B>
</A>
答案 0 :(得分:4)
我甚至不会使用QDomDocument
,也就是说。 QtXml
为此,因为流读取器和编写器类在QtCore中使用起来相对简单。这是我的解决方案,可以进一步扩展到支持其他事情:
<A>
<B>
<C>
.............................
</C>
</B>
</A>
<?xml version="1.0" encoding="UTF-8"?>
<A>
<B/>
</A>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QDebug>
#include <QString>
#include <QFile>
int main()
{
QFile inputFile("testin.xml");
if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "File open error:" << inputFile.errorString();
return 1;
}
QFile outputFile("testout.xml");
if (!outputFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << "File open error:" << outputFile.errorString();
return 1;
}
QXmlStreamReader inputStream(&inputFile);
QXmlStreamWriter outputStream(&outputFile);
outputStream.setAutoFormatting(true);
outputStream.writeStartDocument();
bool ignore = false;
static const QString searchString = "C";
while (!inputStream.atEnd() && !inputStream.hasError())
{
inputStream.readNext();
if (inputStream.isStartElement()) {
QString name = inputStream.name().toString();
if (name != searchString && !ignore)
outputStream.writeStartElement(name);
else
ignore = true;
} else if (inputStream.isEndElement()) {
if (!ignore)
outputStream.writeEndElement();
if (inputStream.name().toString() == searchString)
ignore = false;
}
}
outputStream.writeEndDocument();
return 0;
}
TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp
qmake && make && ./main
如果您仍然坚持使用QtXml
执行此简单任务,则可以执行以下操作:
#include <QDomDocument>
#include <QDomNode>
#include <QDomElement>
#include <QFile>
#include <QDebug>
int main()
{
QFile inputFile("testin.xml");
if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "File open error:" << inputFile.errorString();
return 1;
}
QDomDocument doc;
doc.setContent(&inputFile);
QDomNode searchNode = doc.elementsByTagName("C").item(0);
QDomNode parentNode = searchNode.parentNode();
parentNode.removeChild(searchNode);
qDebug() << doc.toString();
return 0;
}
TEMPLATE = app
TARGET = main
QT = core xml
SOURCES += main.cpp
qmake && make && ./main
"<A>
<B/>
</A>
"