cuốn sách gpt4 ai đã làm

c++ - 删除 XML 文件的特定内容

In lại Tác giả: Walker 123 更新时间:2023-11-28 05:52:35 hai mươi bốn 4
mua khóa gpt4 Nike

在我的 xml 文件中,我有一个节点,其子节点有 2 个属性,我必须删除 1 个整个子节点,同时只考虑 1 个属性。我在下面给出了一个例子

XML 文件:








我必须删除只有“Name”属性的整个子子项,因为 Value 可以更改。

到目前为止我的代码:

void::MainWindow::XML()
{
QString path = ui->lineEdit_7->text();

qDebug()<<>
if(!file.exists() )
{
qDebug() << "Check your file";
}
QDomDocument dom;
dom.setContent(&file);
QDomNodeList nodes = dom.elementsByTagName("ABC");

QDomNodeList loc_childNodes = nodes.at(0).childNodes();

for(int i=0; i
{
QDomNode node = loc_childNodes.at(i);
qDebug() << node.attributes().namedItem("Name").nodeValue(); // I get all Name attributes.

最后一个 qDebug 给了我所有的“名称”属性。我坚持使用此信息删除子项。

biên tập:


ABC
ABC1
ABC3

Chỉnh sửa 2:










我只想删除子项的“SUB”属性。预期结果:





编辑3:

qDebug()<<>
QString path = "File"
QFile inFile(path );
if( !inFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
qDebug( "Failed to open file for reading." );
}

QDomDocument dom;
if( !dom.setContent( &inFile ) )
{
qDebug( "Failed to parse the file into a DOM tree." );
}

QDomElement docElem = dom.documentElement();
QDomNodeList nodes = docElem.elementsByTagName("MAIN");
QDomNodeList loc_childNodes = nodes.at(0).childNodes();
for(int i=0; i
{
QDomNode node = loc_childNodes.at(i);
if( node.nodeName().compare("SUB") == 0 ) {
QDomNode parentNode = node.parentNode();
parentNode.removeChild(node);
}
}
QFile outFile( path);
if( !outFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
{
qDebug( "Failed to open file for writing." );
}

QTextStream stream( &outFile );
stream << dom.toString();
outFile.close();

câu trả lời hay nhất

QDomNode 有方法 removeChild 可能有帮助吗?

来自文档

QDomNode QDomNode::removeChild(const QDomNode & oldChild)

Removes oldChild from the list of children. oldChild must be a direct child of this node. Returns a new reference to oldChild on success or a null node on failure.

Addition 你的代码可能看起来像下面这样

if( node.attributes().namedItem("Name").nodeValue().compare("ABC3") == 0 ) {
QDomNode parentNode = node.parentNode();
parentNode.removeChild(node);
}

Thêm vào到编辑 2

if( node.nodeName().compare("SUB") == 0 ) {
QDomNode parentNode = node.parentNode();
parentNode.removeChild(node);
}

更新到编辑 3. 替换行

QDomElement docElem = dom.documentElement();
QDomNodeList nodes = docElem.elementsByTagName("MAIN");

QDomNodeList nodes = dom.elementsByTagName("MAIN");

并且在 parent.removeChild(node) 之后添加 i-=1,因为元素的数量减少了。并且在调用 outFile.open() 之前不要忘记在 File.close() 中关闭文件("file")

关于c++ - 删除 XML 文件的特定内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34919205/

hai mươi bốn 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress