Qt操作XML

前端之家收集整理的这篇文章主要介绍了Qt操作XML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

“形式良好”(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>

猜你在找的XML相关文章