Use tinyxml to parse and modify XML files

First of all, it is necessary to know which elements the XML file contains:

It is composed of elements, text, or a mixture of both. An element can have attributes, and an element is the part from the start tag to the end tag.

<?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> 

start operation

1. Download the source code of tinyxml from the Internet

 2. Import the header file of tinyxml

#include "./TinyXML/tinyxml.h"

Parsing method:


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;
}

Modification method:


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()));
        }
    }
}

Parsing example:

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;
}

Modified example:

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);
    }
}

Guess you like

Origin blog.csdn.net/caicai_xiaobai/article/details/132087752