Below is my code & xml file. I am trying to read a xml file and store the contents. But its not working. Please help
int ParseConfigFile::populateUserValues ( string &OS, string &dir, string &logPath )
{
QDomDocument doc;
QDomElement element;
QFile file("config_v1.xml");
if ( doc.setContent( file.readAll() ) == false )
开发者_开发技巧 return 1;
element = doc.documentElement();
QDomNodeList list = element.childNodes();
QDomElement firstChild = list.at(0).toElement(); // will return the first child
QDomElement secondChild = list.at(1).toElement();
QDomElement thirdChild = list.at(2).toElement();
QString s1,s2,s3;
s1 = firstChild.text();
s2 = secondChild.text();
s3 = thirdChild.text();
OS = s1.toStdString();
dir = s2.toStdString();
logPath = s3.toStdString();
return 0;
}
and my XML
<?xml version="1.0"?>
<config>
<type>LINUX</type>
<dir>/home/</dir>
<path>/var/log/</path>
</config>
You should instantiate the QDomDocument like this and then your code will work:
if ( doc.setContent(&file) == false )
return 1;
QDomDocument can work with an IO device (like QFile) making this the optimum way to set the QDomDocument's content from a file.
Anyway, if you're trying to write a configuration file reader/writer I suggest you stick with QSettings
QSettings settings("MyCompany", "MyApp");
QString s1,s2,s3;
s1 = settings.value("type").toString();
s2 = secondChild..value("dir").toString();
s3 = thirdChild..value("path").toString();
The configuration file format won't be XML (it will be key=value) but you will hardly ever need to worry about the file itself. To set any value on the file is also easy:
QSettings settings("MyCompany", "MyApp");
settings.setValue("path", "/var/log/");
Your configuration file will look like this:
[General]
path=/var/log/
See: QSettings documentation
精彩评论