使用tinyxml解析和修改XML文件

首先要清楚XML文件包含哪些元素:

他是由元素、文本或者两者混合物组成。元素可以拥有属性,元素是指从开始标签到结束标签的部分。

XML 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<books>
          <book id="1001">
           
                <name>面纱</name>
                <info>请记住我,虽然再见必须说</info>
          </book>
           <book id="1002">
                <name>人生第一次</name>
                <info>愿他们、我们的一生平淡而有意义</info>
          </book>
</books> 

开始操作

1.在网上下载到tinnyxml的源码

2.导入tinyxml的头文件

复制代码
#include "./TinyXML/tinyxml.h"

解析方法:

cpp 复制代码
QString XMLreadwrite::parseIPAddress() const
{
    QList<QString> nodeList;
    nodeList.append("net");
    nodeList.append("fix_ip");
    QString attrText = "ip";

    TiXmlNode *pNode = (TiXmlNode*)FindTextNode(nodeList);
    QString data = ParseNodeData(pNode, attrText);

    return data;
}

修改方法:

cpp 复制代码
void XMLreadwrite::ModifyNodeData(TiXmlNode *pNode, QString text, QString data) const
{
    for(pNode = pNode->FirstChild();
        pNode;
        pNode = pNode->NextSibling())
    {
        if(QString(QLatin1String(pNode->Value())) == text)
        {
            qDebug()<<"......."<<text<<data;
            const char cData[1024] = {0};
            memcpy((void*)cData,data.toStdString().c_str(),data.size());
            //首先清除所有文本
            pNode->Clear();
            //然后插入文本
            TiXmlText  *pValue = new TiXmlText(cData);
            pNode->LinkEndChild(pValue);
            qDebug()<<"Modified successfully"<<QString(QLatin1String(pNode->ToElement()->GetText()));
        }
    }
}

解析例子:

cpp 复制代码
QString XMLreadwrite::parseCodeFormat() const
{
    QList<QString> nodeList;
    nodeList.append("param_video");
    QString attrText = "attr_format";

    TiXmlNode *pNode = (TiXmlNode*)FindTextNode(nodeList);
    QString nodeAttr = QString(QLatin1String(pNode->ToElement()->Attribute("name")));
    QString data = "";
    if(nodeAttr == "Visible")
    {
        data = ParseNodeData(pNode, attrText);
    }

    return data;
}

修改例子:

cpp 复制代码
void XMLreadwrite::modifyCodeFormat(QString data)
{
    QList<QString> nodeList;
    nodeList.append("param_video");
    QString attrText = "attr_format";

    TiXmlNode *pNode = (TiXmlNode*)FindTextNode(nodeList);
    QString nodeAttr = QString(QLatin1String(pNode->ToElement()->Attribute("name")));
    if(nodeAttr == "Visible")
    {
        ModifyNodeData(pNode, attrText, data);
    }
}
相关推荐
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
阳光开朗_大男孩儿9 天前
XML读取和设置例子
xml·java·数据库
悟能不能悟11 天前
在 MyBatis 的xml中,什么时候大于号和小于号可以不用转义
xml·java·mybatis
慌糖11 天前
XML重复查询一条Sql语句??怎么解决
xml·数据库·sql
胖大和尚11 天前
在 XML 节点名称前添加前缀
xml
casual_clover12 天前
Android 中 解析 XML 字符串的几种方式
android·xml
SuperherRo13 天前
Web攻防-XSS跨站&文件类型&功能逻辑&SVG&PDF&SWF&HTML&XML&PMessage&LocalStorage
xml·pdf·html·svg·localstorage·swf·pmessage
'tubug'14 天前
XXE(XML外部实体注入)详解
xml·web安全
不太厉害的程序员18 天前
NC65配置xml找不到Bean
xml·java·后端·eclipse
峥嵘life18 天前
Android xml的Preference设置visibility=“gone“ 无效分析解决
android·xml