加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Qt操作XML

发布时间:2020-12-15 23:29:28 所属栏目:百科 来源:网络整理
导读:“形式良好”(Well Formed)的 XML 文档会遵守前几章介绍过的 XML 语法规则: XML 文档必须有根元素 XML 文档必须有关闭标签 XML 标签对大小写敏感 XML 元素必须被正确的嵌套 XML 属性必须加引号 读取xml: void analysisXML(QString str){QDomDocument doc

“形式良好”(Well Formed)的 XML 文档会遵守前几章介绍过的 XML 语法规则:

XML 文档必须有根元素

XML 文档必须有关闭标签

XML 标签对大小写敏感

XML 元素必须被正确的嵌套

XML 属性必须加引号

读取xml:

void analysisXML(QString str)
{
	QDomDocument doc;
	QFile xmlFile(str);
	if(!xmlFile.open(QIODevice::ReadOnly))
	{
		return;
	}
	//This function parses(解析) the XML document from the byte array data 
	//and sets it as the content(内容) of the document. 
	//It tries to detect(检测) the encoding(编码) of the document as required by the XML specification(规范).
	if(!doc.setContent(&xmlFile))
	{
		xmlFile.close();
		return;
	}
	xmlFile.close(); 
	
	QDomElement element=doc.documentElement();  ///Returns the root element of the document.
	for(QDomNode node=element.firstChild(); !node.isNull(); node=node.nextSibling())
	{
		QDomElement e=node.toElement();
		qDebug()<<e.tagName()<<":"<<e.text();
	}
	
	//QDomElement docEle=doc.documentElement();
	//QDomNode n=docEle.firstChild();
	//while(!n.isNull())
	//{
	//	QDomElement e=n.toElement();   ///try to convert the node to an element
	//	if(!e.isNull())
	//	{
	//		qDebug()<<e.tagName()<<":"<<e.text();
	//	}
	//	n= n.nextSibling();
	//}
	xmlFile.close();
}

写xml:

void writeXML()
{
	QFile file("writeXML.xml");
	if(!file.open(QIODevice::WriteOnly|QIODevice::Truncate))
	{
		return;
	}
	QDomDocument doc;
	QDomProcessingInstruction instruction;
	instruction=doc.createProcessingInstruction("xml","version="1.0" encoding="UTF-8"");
	doc.appendChild(instruction);

	QDomElement root=doc.createElement(QIODevice::tr("data"));
	doc.appendChild(root);
	QDomElement StartWeek=doc.createElement(QObject::tr("startweek"));  
	QDomElement ReadNumber=doc.createElement(QObject::tr("readnum"));  
	QDomElement AlarmTime=doc.createElement(QObject::tr("alarm"));  
	QDomElement AlarmPrompt=doc.createElement(QObject::tr("prompt"));

	QDomText text;  
	text=doc.createTextNode("2010-03-01");  
	StartWeek.appendChild(text);  
	text=doc.createTextNode("2");  
	ReadNumber.appendChild(text);  
	text=doc.createTextNode("10");  
	AlarmTime.appendChild(text);  
	text=doc.createTextNode("vibration");  
	AlarmPrompt.appendChild(text);  
	root.appendChild(StartWeek);  
	root.appendChild(ReadNumber);  
	root.appendChild(AlarmTime);  
	root.appendChild(AlarmPrompt); 

	QTextStream out(&file);  
	doc.save(out,4);  
	file.close();  
}

如下xml:

<?xml version="1.0" encoding="UTF-8"?>

  <data>
    
     <startweek>2010-03-01</startweek>
   
     <readnum>3</readnum>
   
     <alarm>7</alarm>
    
     <prompt>Alarm Window</prompt>

  </data>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读