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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值