QT XML文件 修改节点

感谢:l270378034的帮助

源xml文件:

<kdevelop>
   <general>
     <author>zeki</author>
     <email>caizhiming@tom.com</email>
   </general>
</kdevelop>

源程序:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
     changeSave();
}

MainWindow::~MainWindow()
{
    delete ui;
}
bool MainWindow::openXmlFile(QString FilePath)
{
    QFile file( FilePath );
        if( !file.open( QFile::ReadOnly | QFile::Text  ) )
        {
            qDebug() << QObject::tr("error::ParserXML->OpenXmlFile->file.open->%s\n") << FilePath;

            return false;
        }

        if( !m_doc.setContent( &file ) )
        {
            qDebug() << QObject::tr("error::ParserXML->OpenXmlFile->doc.setContent\n") << FilePath;

            file.close();
            return false;
        }
        file.close();
        return true;
}
bool MainWindow::changeSave()
{
    if(!openXmlFile("/home/qust/qt/XML/2.xml"))
        {
            return false;
        }
        //修改保存xml
    QDomElement root = m_doc.documentElement();
       if(root.tagName()!= "kdevelop")
           return false;
       QDomNode n = root.firstChild();
       while ( !n.isNull() )
       {
           QDomElement e = n.toElement();
           if( !e.isNull())
           {
                       if( e.nodeName() == "general" )
                       {
                           QDomNodeList list = e.childNodes(); //获得元素e的所有子节点的列表
                           for(int a=0; a<list.count(); a++) //遍历该列表
                           {
                               QDomNode node = list.at(a);
                               if(node.isElement())
                               {
                                   if( node.nodeName() == "author" )
                                   { QDomNode oldnode = node.firstChild();     //标签之间的内容作为节点的子节点出现,得到原来的子节点
                                       node.firstChild().setNodeValue("csdn");   //用提供的value值来设置子节点的内容
                                       QDomNode newnode = node.firstChild();     //值修改过后
                                       node.replaceChild(newnode,oldnode);      //调用节点的replaceChild方法实现修改功能
                                   }
                                   if( node.nodeName() == "email" )
                                   {
                                       QDomNode oldnode = node.firstChild();
                                       node.firstChild().setNodeValue("test@tom.com");
                                       QDomNode newnode = node.firstChild();
                                       node.replaceChild(newnode,oldnode);
                                   }
                               }
                           }
                       }
                   }
           n = n.nextSibling();
             }
             QFile filexml("/home/qust/qt/XML/2.xml");
             if( !filexml.open( QFile::WriteOnly | QFile::Truncate) ){
                 qWarning("error::ParserXML->writeOperateXml->file.open\n");
                 return false;
                    }
                    QTextStream ts(&filexml);
                    ts.reset();
                    ts.setCodec("utf-8");
                    m_doc.save(ts, 4, QDomNode::EncodingFromTextStream);
                    filexml.close();
                    return true;


}

运行后:

<kdevelop>
  <general>
    <author>csdn</author>
    <email>test@tom.com</email>
  </general>
</kdevelop>


QDomNode QDomNode::nextSibling () const

Returns the next sibling in the document tree. Changing the returned node will also change the node in the document tree.

If you have XML like this:

 <h1>Heading</h1>
 <p>The text...</p>
 <h2>Next heading</h2>


and this QDomNode represents the <p> tag, nextSibling() will return the node representing the <h2> tag.


sibling 1.同层级 2.同辈 3.兄弟或姊妹。 4.同胞 Sibling 1.同胞兄妹


QT XML文件主要用于存储数据结构化的信息,通过XML(Extensible Markup Language)标准格式来组织文本数据。在QT项目中操作XML文件通常涉及到解析、修改以及生成XML内容等操作。 为了在QT应用程序中添加节点XML文件,你可以使用Qt库中的`QXmlStreamWriter`类来进行XML文档的操作。下面是一个简单的步骤来帮助你理解如何使用这个类: ### 步骤 1: 创建一个新的XML文件 ```cpp QFile file("example.xml"); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "无法打开文件"; } QXmlStreamWriter writer(&file); writer.writeStartDocument(); ``` ### 步骤 2: 添加根元素及子元素 ```cpp writer.writeStartElement("root"); // 开始新的元素 writer.writeAttribute("id", "1"); // 添加属性 // 添加子元素 writer.writeStartElement("child1"); writer.writeCharacters("Some text in child element"); writer.writeEndElement(); // 结束当前元素 // 继续添加更多子元素... writer.writeEndElement(); // 结束"root"元素 writer.writeEndDocument(); file.close(); ``` ### 相关问题: 1. **如何读取XML文件并解析其中的数据?** 使用`QXmlStreamReader`可以读取XML文件,并逐行解析其内容。这适用于需要从XML文件中提取特定数据的情况。 2. **如何使用Qt进行动态生成XML字符串?** `QXmlStreamWriter`不仅用于写入XML文件,也可以直接生成XML字符串。这对于需要在内存中构建XML文档而不需要持久化存储到文件的应用场景非常有用。 3. **在QT应用中处理错误情况,例如文件不存在或权限不足?** 当尝试打开或写入文件时,如果遇到错误,如文件不存在或没有足够的权限,QT会抛出异常。你应该捕获这些异常并在适当的位置进行错误处理,比如弹出警告消息给用户。 以上步骤提供了一个基础框架来开始在QT应用中处理XML文件。每个步骤都包含了一些基本的示例代码片段,旨在帮助开发者了解如何利用Qt库中的工具来进行XML的创建、修改和读取操作。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值