qtxml生成与解析

目录

xml生成:

xml解析:


xml生成:

void Qxml::setTml()
{
    QDomDocument doc;//xml文档树的创建
    //xml文档树的指令版本必有的
    QDomProcessingInstruction pi=doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"utf-8\"");
    doc.appendChild(pi);//xml文档树的添加
    QDomElement root=doc.createElement("root");//创建根元素 一般有且只有一个
    doc.appendChild(root);//xml文档树的添加
    ///      大致的格式基本如此
    /// ff0
    /// ff1
    /// 添加规则 *注意父元素添的是元素 *子元素一般添的是文本 依赖文档树doc对象生成
    QDomElement baotou=doc.createElement("报头");
    root.appendChild(baotou);
    QDomElement baowen=doc.createElement("报文");
    root.appendChild(baowen);
    //报头添加
    {
        QDomElement a1=doc.createElement("报头内容");
        QDomElement a1_1=doc.createElement("子内容1");
        a1_1.appendChild(doc.createTextNode("火力覆盖"));
        QDomElement a1_2=doc.createElement("子内容2");
        a1_2.appendChild(doc.createTextNode("直接打击"));
        a1.appendChild(a1_1);
        a1.appendChild(a1_2);
        QDomElement a2=doc.createElement("报头内容");
        a2.appendChild(doc.createTextNode("报头内容222"));
        QDomElement a3=doc.createElement("报头内容");
        a3.appendChild(doc.createTextNode("报头内容333"));
        baotou.appendChild(a1);
        baotou.appendChild(a2);
        baotou.appendChild(a3);
    }
    //报文
    {
        QDomElement a1=doc.createElement("报文内容");
        QDomElement a1_1=doc.createElement("子内容1");
        a1_1.appendChild(doc.createTextNode("火力覆盖"));
        QDomElement a1_2=doc.createElement("子内容2");
        a1_2.appendChild(doc.createTextNode("直接打击"));
        a1.appendChild(a1_1);
        a1.appendChild(a1_2);
        QDomElement a2=doc.createElement("报文内容");
        a2.appendChild(doc.createTextNode("报文内容222"));
        QDomElement a3=doc.createElement("报文内容");
        a3.appendChild(doc.createTextNode("报文内容333"));
        baowen.appendChild(a1);
        baowen.appendChild(a2);
        baowen.appendChild(a3);
    }
    //写入文件
    QFile fi("baowen.xml");
    if(!fi.open(QIODevice::WriteOnly|QIODevice::Text))
    {return;}
    else {
        fi.write(doc.toByteArray());
        fi.close();
        qDebug()<<"写入成功";
    }
}

xml解析:

void Qxml::getxml()
{
    QFile f("ff.xml");//
    f.open(QIODevice::ReadOnly|QIODevice::Text);
    QByteArray bytes=f.readAll();
    f.close();
    QDomDocument doc;//xml文档树
    doc.setContent(bytes);//必写如果写第二个参数可以为false,实际用的话一个参数就好了
    QDomElement root=doc.documentElement();//必写返回xml文档的根元素(xml一般有且只有一个根元素)
    ///核心:拿到元素 获取元素里面的节点 进行判断是(文本节点直接输出)是(元素节点再次进行解析)
    ///ff1 这就是一个元素(element) 他的节点(node)为1  节点类型是文本节点
    ///                ffff 就是一个元素 节点为1  节点类型是 元素节点
    ///  ff0    ff00 是一个元素 节点为1  节点类型是  文本节点
    ///  ff1    ff11 是一个元素 节点为1  节点类型是  文本节点
    ///               //解了好久悟性太差了哎
    QDomNodeList ns=root.childNodes();//获取根元素下所有同一级别 子节点 的个数
    qDebug()<

你可能感兴趣的:(qt)