本文整理汇总了C++中QDomNode::firstChild方法的典型用法代码示例。如果您正苦于以下问题:C++ QDomNode::firstChild方法的具体用法?C++ QDomNode::firstChild怎么用?C++ QDomNode::firstChild使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QDomNode
的用法示例。
在下文中一共展示了QDomNode::firstChild方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: parseXml
void DataManagerImpl::parseXml(QDomNode& dataManagerNode, QString rootPath)
{
// look in the toolmanager, for backwards compatibility (2014-02-21)
QDomNode toolManagerNode = dataManagerNode.parentNode().namedItem("toolManager");
QDomNode registrationHistory = dataManagerNode.namedItem("registrationHistory");
if (registrationHistory.isNull())
registrationHistory = toolManagerNode.namedItem("registrationHistory");
m_rMpr_History->parseXml(registrationHistory);
QDomNode landmarksNode = dataManagerNode.namedItem("landmarkprops");
QDomElement landmarkNode = landmarksNode.firstChildElement("landmarkprop");
for (; !landmarkNode.isNull(); landmarkNode = landmarkNode.nextSiblingElement("landmarkprop"))
{
LandmarkProperty landmarkProp;
landmarkProp.parseXml(landmarkNode);
mLandmarkProperties[landmarkProp.getUid()] = landmarkProp;
//std::cout << "Loaded landmarkprop with name: " << landmarkProp.getName() << std::endl;
emit landmarkPropertiesChanged();
}
QDomNode patientLandmarksNode = dataManagerNode.namedItem("landmarks");
if (patientLandmarksNode.isNull())
patientLandmarksNode = toolManagerNode.namedItem("landmarks");
mPatientLandmarks->parseXml(patientLandmarksNode);
// All images must be created from the DataManager, so the image nodes are parsed here
std::map<DataPtr, QDomNode> datanodes;
QDomNode child = dataManagerNode.firstChild();
for (; !child.isNull(); child = child.nextSibling())
{
if (child.nodeName() == "data")
{
DataPtr data = this->loadData(child.toElement(), rootPath);
if (data)
datanodes[data] = child.toElement();
}
}
// parse xml data separately: we want to first load all data
// because there might be interdependencies (cx::DistanceMetric)
for (std::map<DataPtr, QDomNode>::iterator iter = datanodes.begin(); iter != datanodes.end(); ++iter)
{
iter->first->parseXml(iter->second);
}
emit dataAddedOrRemoved();
//we need to make sure all images are loaded before we try to set an active image
child = dataManagerNode.firstChild();
while (!child.isNull())
{
if (child.toElement().tagName() == "center")
{
const QString centerString = child.toElement().text();
if (!centerString.isEmpty())
{
Vector3D center = Vector3D::fromString(centerString);
this->setCenter(center);
}
}
child = child.nextSibling();
}
}
示例2: parseDistroNews
/*
* Parses the raw XML contents from the Distro RSS news feed
* Creates and returns a string containing a HTML code with latest 10 news
*/
QString MainWindow::parseDistroNews()
{
QString html;
LinuxDistro distro = UnixCommand::getLinuxDistro();
if (distro == ectn_ARCHLINUX || distro == ectn_ARCHBANGLINUX)
{
html = "<p align=\"center\"><h2>" + StrConstants::getArchLinuxNews() + "</h2></p><ul>";
}
else if (distro == ectn_CHAKRA)
{
html = "<p align=\"center\"><h2>" + StrConstants::getChakraNews() + "</h2></p><ul>";
}
else if (distro == ectn_MANJAROLINUX)
{
html = "<p align=\"center\"><h2>" + StrConstants::getManjaroLinuxNews() + "</h2></p><ul>";
}
QString lastBuildDate;
QString rssPath = QDir::homePath() + QDir::separator() + ".config/octopi/distro_rss.xml";
QDomDocument doc("rss");
int itemCounter=0;
QFile file(rssPath);
if (!file.open(QIODevice::ReadOnly)) return "";
if (!doc.setContent(&file)) {
file.close();
return "";
}
file.close();
QDomElement docElem = doc.documentElement(); //This is rss
QDomNode n = docElem.firstChild(); //This is channel
n = n.firstChild();
while(!n.isNull()) {
QDomElement e = n.toElement();
if(!e.isNull())
{
if (e.tagName() == "lastBuildDate")
{
lastBuildDate = e.text();
}
else if(e.tagName() == "item")
{
//Let's iterate over the 10 lastest "item" news
if (itemCounter == 10) break;
QDomNode text = e.firstChild();
QString itemTitle;
QString itemLink;
QString itemDescription;
QString itemPubDate;
while(!text.isNull())
{
QDomElement eText = text.toElement();
if(!eText.isNull())
{
if (eText.tagName() == "title")
{
itemTitle = "<h3>" + eText.text() + "</h3>";
}
else if (eText.tagName() == "link")
{
itemLink = Package::makeURLClickable(eText.text());
if (UnixCommand::getLinuxDistro() == ectn_MANJAROLINUX) itemLink += "<br>";
}
else if (eText.tagName() == "description")
{
itemDescription = eText.text();
//itemDescription = itemDescription.remove(QRegExp("\\n"));
itemDescription += "<br>";
}
else if (eText.tagName() == "pubDate")
{
itemPubDate = eText.text();
itemPubDate = itemPubDate.remove(QRegExp("\\n"));
int pos = itemPubDate.indexOf("+");
if (pos > -1)
{
itemPubDate = itemPubDate.mid(0, pos-1).trimmed() + "<br>";
}
}
}
text = text.nextSibling();
}
html += "<li><p>" + itemTitle + " " + itemPubDate + "<br>" + itemLink + itemDescription + "</p></li>";
itemCounter++;
}
//.........这里部分代码省略.........
示例3: readSigset
/**** BEE ****/
FileList BEE::readSigset(const File &sigset, bool ignoreMetadata)
{
FileList fileList;
#ifndef BR_EMBEDDED
QDomDocument doc(sigset.fileName());
QFile file(sigset.resolved());
bool success;
success = file.open(QIODevice::ReadOnly); if (!success) qFatal("Unable to open %s for reading.", qPrintable(sigset));
success = doc.setContent(&file);
file.close();
if (!success) {
qWarning("Unable to parse %s.", qPrintable(sigset));
return fileList;
}
QDomElement docElem = doc.documentElement();
if (docElem.nodeName() != "biometric-signature-set")
return fileList;
QDomNode subject = docElem.firstChild();
while (!subject.isNull()) {
// Looping through subjects
QDomNode fileNode = subject.firstChild();
QDomElement d = subject.toElement();
QString name = d.attribute("name");
while (!fileNode.isNull()) {
// Looping through files
File file("", name);
QDomElement e = fileNode.toElement();
QDomNamedNodeMap attributes = e.attributes();
for (int i=0; i<attributes.length(); i++) {
const QString key = attributes.item(i).nodeName();
const QString value = attributes.item(i).nodeValue();
if (key == "file-name") file.name = value;
else if (!ignoreMetadata) file.set(key, value);
}
// add bounding boxes, if they exist (will be child elements of <presentation>)
if (fileNode.hasChildNodes()) {
QList<QRectF> rects;
QDomNodeList bboxes = fileNode.childNodes();
for (int i=0; i<bboxes.length(); i++) {
QDomElement bbox = bboxes.at(i).toElement();
qreal x = bbox.attribute("x").toDouble();
qreal y = bbox.attribute("y").toDouble();
qreal width = bbox.attribute("width").toDouble();
qreal height = bbox.attribute("height").toDouble();
rects += QRectF(x, y, width, height);
}
file.setRects(rects);
}
if (file.name.isEmpty()) qFatal("Missing file-name in %s.", qPrintable(sigset));
fileList.append(file);
fileNode = fileNode.nextSibling();
}
subject = subject.nextSibling();
}
#else // BR_EMBEDDED
(void) sigset;
(void) ignoreMetadata;
#endif // BR_EMBEDDED
return fileList;
}
示例4: adjustNewstuffFile
bool Upload::adjustNewstuffFile(const Package &package)
{
if (m_xml.isNull()) {
QTemporaryFile tempFile(QDir::tempPath() + "/monav-maps-XXXXXX.xml");
tempFile.setAutoRemove(false);
tempFile.open();
QString monavFilename = tempFile.fileName();
tempFile.close();
QProcess wget;
QStringList const arguments = QStringList() << "http://files.kde.org/marble/newstuff/maps-monav.xml" << "-O" << monavFilename;
wget.start("wget", arguments);
wget.waitForFinished(1000 * 60 * 60 * 12); // wait up to 12 hours for download to complete
if (wget.exitStatus() != QProcess::NormalExit || wget.exitCode() != 0) {
qDebug() << "Failed to download newstuff file from files.kde.org";
Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to sync newstuff file: " + wget.readAllStandardError());
return false;
}
QFile file(monavFilename);
if (!file.open(QFile::ReadOnly)) {
qDebug() << "Failed to open newstuff file" << monavFilename;
Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to open newstuff file.");
return false;
}
if ( !m_xml.setContent( &file ) ) {
qDebug() << "Cannot parse newstuff xml file.";
Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to parse newstuff .xml file.");
return false;
}
QFile::remove(monavFilename);
}
QDomElement root = m_xml.documentElement();
QDomNodeList regions = root.elementsByTagName( "stuff" );
for ( unsigned int i = 0; i < regions.length(); ++i ) {
QDomNode node = regions.item( i );
if (!node.namedItem("payload").isNull()) {
QUrl url = node.namedItem("payload").toElement().text();
QFileInfo fileInfo(url.path());
if (fileInfo.fileName() == package.file.fileName()) {
QString removeFile;
QDomNode dateNode = node.namedItem("releasedate");
if (!dateNode.isNull()) {
dateNode.removeChild(dateNode.firstChild());
dateNode.appendChild(m_xml.createTextNode(releaseDate()));
}
QDomNode versionNode = node.namedItem("version");
if (!versionNode.isNull()) {
double version = versionNode.toElement().text().toDouble();
versionNode.removeChild(versionNode.firstChild());
versionNode.appendChild(m_xml.createTextNode(QString::number(version+0.1, 'f', 1)));
}
QDomNode payloadNode = node.namedItem("payload");
payloadNode.removeChild(payloadNode.firstChild());
if (fileInfo.dir().dirName() != targetDir()) {
removeFile = QString("/home/marble/web/monav/%1/%2").arg(fileInfo.dir().dirName()).arg(package.file.fileName());
qDebug() << "Going to remove the old file " << removeFile;
}
QString payload = "http://files.kde.org/marble/monav/%1/%2";
payload = payload.arg(targetDir()).arg(package.file.fileName());
payloadNode.appendChild(m_xml.createTextNode(payload));
return removeFile.isEmpty() ? uploadNewstuff() : (uploadNewstuff() && deleteRemoteFile(removeFile));
}
}
}
QDomNode stuff = root.appendChild(m_xml.createElement("stuff"));
stuff.toElement().setAttribute("category", "marble/routing/monav");
QDomNode nameNode = stuff.appendChild(m_xml.createElement("name"));
nameNode.toElement().setAttribute("lang", "en");
QString name = "%1 / %2 (%3)";
if (package.region.country().isEmpty()) {
name = name.arg(package.region.continent()).arg(package.region.name());
name = name.arg(package.transport);
} else {
name = "%1 / %2 / %3 (%4)";
name = name.arg(package.region.continent()).arg(package.region.country());
name = name.arg(package.region.name()).arg(package.transport);
}
nameNode.appendChild(m_xml.createTextNode(name));
QDomNode authorNode = stuff.appendChild(m_xml.createElement("author"));
authorNode.appendChild(m_xml.createTextNode("Automatically created from map data assembled by the OpenStreetMap community"));
QDomNode licenseNode = stuff.appendChild(m_xml.createElement("license"));
licenseNode.appendChild(m_xml.createTextNode("Creative Commons by-SA 2.0"));
QDomNode summaryNode = stuff.appendChild(m_xml.createElement("summary"));
QString summary = "Requires KDE >= 4.6: Offline Routing in %1, %2";
summary = summary.arg(package.region.name()).arg(package.region.continent());
summaryNode.appendChild(m_xml.createTextNode(summary));
QDomNode versionNode = stuff.appendChild(m_xml.createElement("version"));
versionNode.appendChild(m_xml.createTextNode("0.1"));
QDomNode dateNode = stuff.appendChild(m_xml.createElement("releasedate"));
dateNode.appendChild(m_xml.createTextNode(releaseDate()));
//.........这里部分代码省略.........
示例5: searchData
void KFFOpt_scenery::searchData( QFile* file )
{
QDomDocument doc;
QDomElement root;
QDomNode parent;
QDomNode child;
QDomElement e_parent;
QDomElement e_child;
KFFScenarioData scenario;
QString name;
QStringList list;
QStringList::Iterator it;
if ( doc.setContent( file ) )
{
root = doc.documentElement();
parent = root.firstChild();
e_parent = parent.toElement();
if ( !e_parent.isNull() )
{
if ( e_parent.tagName() == "description" )
{
list = e_parent.text().split("\n");
for (it = list.begin() ; it != list.end() ; it++ )
{
*it = it->simplified();
}
scenario.description = list.join("\n");
parent = parent.nextSibling();
}
}
parent = parent.firstChild();
name = file->fileName().section( '/', -1, -1 ).remove( ".xml" );
while ( !parent.isNull() )
{
e_parent = parent.toElement();
if ( !e_parent.isNull() )
{
if ( e_parent.tagName() == "entry" )
{
child = parent.firstChild();
while ( !child.isNull() )
{
e_child = child.toElement();
if ( !e_child.isNull() )
{
if ( e_child.tagName() == "type" )
{
scenario.type = e_child.text();
}
}
child = child.nextSibling();
}
}
if ( e_parent.tagName() == "description" )
{
list = e_parent.text().split("\n");
for (it = list.begin() ; it != list.end() ; it++ )
{
*it = it->simplified();
}
scenario.description = list.join("\n");
}
}
parent = parent.nextSibling();
}
if ( !m_scenarii.contains( name ) )
{
m_scenarii[name] = scenario;
}
}
else
{
qDebug() << file->fileName() << "is not a valide xml file" ;
}
}
示例6: writeToDB
int LoadReport::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
int errLine = 0;
int errCol = 0;
QDomDocument doc;
if (! doc.setContent(pdata, &errMsg, &errLine, &errCol))
{
errMsg = (TR("<font color=red>Error parsing file %1: %2 on "
"line %3 column %4</font>")
.arg(_filename).arg(errMsg).arg(errLine).arg(errCol));
return -1;
}
QDomElement root = doc.documentElement();
if(root.tagName() != "report")
{
errMsg = TR("<font color=red>XML Document %1 does not have root"
" node of report</font>")
.arg(_filename);
return -2;
}
for(QDomNode n = root.firstChild(); !n.isNull(); n = n.nextSibling())
{
if(n.nodeName() == "name")
_name = n.firstChild().nodeValue();
else if(n.nodeName() == "description")
_comment = n.firstChild().nodeValue();
}
QString report_src = doc.toString();
if(_filename.isEmpty())
{
errMsg = TR("<font color=orange>The document %1 does not have"
" a report name defined</font>")
.arg(_filename);
return -3;
}
if (_grade == INT_MIN)
{
QSqlQuery minOrder;
minOrder.prepare("SELECT MIN(report_grade) AS min "
"FROM report "
"WHERE (report_name=:name);");
minOrder.bindValue(":name", _name);
minOrder.exec();
if (minOrder.first())
_grade = minOrder.value(0).toInt();
else if (minOrder.lastError().type() != QSqlError::NoError)
{
QSqlError err = minOrder.lastError();
errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
return -4;
}
else
_grade = 0;
}
else if (_grade == INT_MAX)
{
QSqlQuery maxOrder;
maxOrder.prepare("SELECT MAX(report_grade) AS max "
"FROM report "
"WHERE (report_name=:name);");
maxOrder.bindValue(":name", _name);
maxOrder.exec();
if (maxOrder.first())
_grade = maxOrder.value(0).toInt();
else if (maxOrder.lastError().type() != QSqlError::NoError)
{
QSqlError err = maxOrder.lastError();
errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
return -5;
}
else
_grade = 0;
}
QSqlQuery select;
QSqlQuery upsert;
int reportid = -1;
int pkgheadid = -1;
int pkgitemid = -1;
/* The following ugliness exists to avoid
ERROR: duplicate key violates unique constraint "report_name_grade_idx"
*/
QString rptselect("SELECT report_id, -1, -1"
" FROM report "
" WHERE ((report_name=:name) "
" AND (report_grade=:grade) );");
if (pkgname.isEmpty())
{
select.prepare(rptselect);
select.bindValue(":name", _name);
select.bindValue(":grade", _grade);
select.exec();
if(select.first())
//.........这里部分代码省略.........
示例7: main
int main(int argc, char *argv[])
{
QString title;
title = title + "********************************************************************* \n";
title = title + " * Create from XML * \n";
title = title + " * This tool create a SQL DDL script file from a XML schema file * \n";
title = title + " * created by ODKToMySQL. * \n";
title = title + " * * \n";
title = title + " * This tool is usefull when dealing with multiple versions of an * \n";
title = title + " * ODK survey that were combined into a common XML schema using * \n";
title = title + " * compareCreateXML. * \n";
title = title + " * * \n";
title = title + " * This tool is part of ODK Tools (c) ILRI-RMG, 2015 * \n";
title = title + " * Author: Carlos Quiros ([email protected] / [email protected]) * \n";
title = title + " ********************************************************************* \n";
TCLAP::CmdLine cmd(title.toUtf8().constData(), ' ', "1.0");
TCLAP::ValueArg<std::string> inputArg("i","input","Input create XML file",true,"","string");
TCLAP::ValueArg<std::string> outputArg("o","output","Output SQL file",false,"./create.sql","string");
cmd.add(inputArg);
cmd.add(outputArg);
//Parsing the command lines
cmd.parse( argc, argv );
//Getting the variables from the command
QString input = QString::fromUtf8(inputArg.getValue().c_str());
QString output = QString::fromUtf8(outputArg.getValue().c_str());
idx = 0;
if (input != output)
{
if (QFile::exists(input))
{
//Openning and parsing input file A
QDomDocument docA("input");
QFile fileA(input);
if (!fileA.open(QIODevice::ReadOnly))
{
log("Cannot open input file");
return 1;
}
if (!docA.setContent(&fileA))
{
log("Cannot parse input file");
fileA.close();
return 1;
}
fileA.close();
QDomElement rootA = docA.documentElement();
if (rootA.tagName() == "XMLSchemaStructure")
{
QFile file(output);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
log("Cannot create output file");
return 1;
}
QDateTime date;
date = QDateTime::currentDateTime();
QTextStream out(&file);
out << "-- Code generated by createFromXML" << "\n";
out << "-- Created: " + date.toString("ddd MMMM d yyyy h:m:s ap") << "\n";
out << "-- by: createFromXML Version 1.0" << "\n";
out << "-- WARNING! All changes made in this file might be lost when running createFromXML again" << "\n\n";
QDomNode lkpTables = docA.documentElement().firstChild();
QDomNode tables = docA.documentElement().firstChild().nextSibling();
if (!lkpTables.isNull())
{
procLKPTables(lkpTables.firstChild(),out);
}
if (!tables.isNull())
{
procTables(tables.firstChild(),out);
}
}
else
{
log("Input document is not a XML create file");
return 1;
}
}
else
{
log("Input file does not exists");
return 1;
}
}
else
{
log("Fatal: Input files and output file are the same.");
//.........这里部分代码省略.........
示例8: if
void Parser3::ParseUserEntry( QDomNode Node, UserPtr Info ) {
QDomNode Child = Node.firstChild();
/// Just fill it up with some video feeds, if not already assigned
if( Info->Favorites.isNull() ) {
Info->Favorites = new VideoFeed;
Info->Favorites->Type = VideoFeed::FT_UserFavorites;
Info->Favorites->ParsedPages = 0;
Info->Favorites->HasFullFeed = false;
} if( Info->Uploads.isNull() ) {
Info->Uploads = new VideoFeed;
Info->Uploads->Type = VideoFeed::FT_UserUploads;
Info->Uploads->ParsedPages = 0;
Info->Uploads->HasFullFeed = false;
} if( Info->Playlists.isNull() ) {
Info->Playlists = new PlaylistFeed;
Info->Playlists->ParsedPages = 0;
Info->Playlists->HasFullFeed = false;
Info->Playlists->Type = PlaylistFeed::FT_UserPlaylists;
}
while( !Child.isNull() )
{
QString NodeName = Child.nodeName();
if( NodeName == "published" )
{
Info->Joined = QDate::fromString( Child.namedItem("#text").nodeValue(), Qt::ISODate );
}
else if( NodeName == "title" )
{
Info->Title = Child.namedItem("#text").nodeValue();
}
else if( NodeName == "author" )
{
Info->Author = Child.namedItem("name").namedItem("#text").nodeValue();
}
else if( NodeName == "yt:age" )
{
Info->Age = Child.namedItem("#text").nodeValue().toInt();
}
else if( NodeName == "yt:aboutMe" )
{
Info->Description = Child.namedItem("#text").nodeValue();
}
else if( NodeName == "gd:feedLink" )
{
QString RelValue = Child.attributes().namedItem("rel").nodeValue();
if( RelValue == "http://gdata.youtube.com/schemas/2007#user.favorites" )
{
Info->Favorites->Size = Child.attributes().namedItem("countHint").nodeValue().toInt();
}
else if( RelValue == "http://gdata.youtube.com/schemas/2007#user.playlists" )
{
Info->Playlists->Size = Child.attributes().namedItem("countHint").nodeValue().toInt();
}
else if( RelValue == "http://gdata.youtube.com/schemas/2007#user.uploads" )
{
Info->Uploads->Size = Child.attributes().namedItem("countHint").nodeValue().toInt();
Info->TotalUploads = Info->Uploads->Size;
}
}
else if( NodeName == "yt:firstName" )
{
Info->FirstName = Child.namedItem("#text").nodeValue();
}
else if( NodeName == "yt:lastName" )
{
Info->LastName = Child.namedItem("#text").nodeValue();
}
else if( NodeName == "yt:statistics" )
{
Info->Subscribers = Child.attributes().namedItem("subscriberCount").nodeValue().toInt();
Info->ChannelsViews = Child.attributes().namedItem("viewCount").nodeValue().toInt();
Info->TotalViews = Child.attributes().namedItem("totalUploadViews").nodeValue().toInt();
}
else if( NodeName == "media:thumbnail" )
{
Info->UrlThumbnail = QUrl( Child.attributes().namedItem("url").nodeValue() );
}
Child = Child.nextSibling();
}
/// Set some important information about the feeds :)
Info->Favorites->NextPageInFeed = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1/favorites?v=2&start-index=1&max-results=50").arg(Info->Author));
Info->Uploads->NextPageInFeed = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1/uploads?v=2&start-index=1&max-results=50").arg(Info->Author));
Info->Playlists->NextPageInFeed = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1/playlists?v=2&start-index=1&max-results=50").arg(Info->Author));
Info->Favorites->Author = Info->Author;
Info->Favorites->Title = QString("%1 Favorites").arg(Info->Author);
Info->Favorites->UrlThumbnail = Info->UrlThumbnail;
Info->Favorites->UrlAuthor = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1?v=2").arg(Info->Author));
Info->Uploads->Author = Info->Author;
Info->Uploads->Title = QString("%1 Uploads").arg(Info->Author);
Info->Uploads->UrlThumbnail = Info->UrlThumbnail;
Info->Uploads->UrlAuthor = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1?v=2").arg(Info->Author));
Info->Playlists->Author = Info->Author;
Info->Playlists->Title = QString("%1 Playlists").arg(Info->Author);
//.........这里部分代码省略.........
示例9: main
int main(int argc, char *argv[])
{
if (argc > 1)
{
QApplication application(argc, argv, FALSE);
application.addLibraryPath(".");
QString databaseURL;
QString username;
QString passwd;
QString arguments;
QString xml_file = QString::null;
int report_grade = 0;
for (int counter = 1; counter < argc; counter++)
{
arguments = argv[counter];
if (arguments.contains("-databaseURL="))
databaseURL = arguments.right(arguments.length() - 13);
else if (arguments.contains("-username="))
username = arguments.right(arguments.length() - 10);
else if (arguments.contains("-passwd="))
passwd = arguments.right(arguments.length() - 8);
else if (arguments.contains("-f="))
xml_file = arguments.right(arguments.length() - 3);
else if (arguments.contains("-grade="))
report_grade = (arguments.right(arguments.length() - 7)).toInt();
}
QString report_name = QString::null;
QString report_desc = QString::null;
QString report_src = QString::null;
if(xml_file != "") {
QFile file(xml_file);
if(file.open( IO_ReadOnly )) {
QDomDocument doc;
QString errMsg;
int errLine, errCol;
if(doc.setContent(&file, &errMsg, &errLine, &errCol)) {
QDomElement root = doc.documentElement();
if(root.tagName() == "report") {
for(QDomNode n = root.firstChild();
!n.isNull(); n = n.nextSibling() ) {
if(n.nodeName() == "name") {
report_name = n.firstChild().nodeValue();
} else if(n.nodeName() == "description") {
report_desc = n.firstChild().nodeValue();
}
}
report_src = doc.toString();
if(report_name == "") {
printf("The document %s does not have a report name defined\n", (const char*)xml_file);
}
} else {
printf("XML Document %s does not have root node of report\n",(const char*)xml_file);
}
} else {
printf("Error parsing file %s: %s on line %d column %d\n",
(const char*)xml_file, (const char*)errMsg, errLine, errCol);
}
} else {
printf("Could not open the specified file: %s\n", (const char*)xml_file);
}
} else {
printf("You must specify an XML file to load by using the -f= parameter.\n");
}
if(report_name == "" || report_src == "") {
// an error message already should have been displayed to the user
exit(-1);
}
if ( (databaseURL != "") &&
(username != "") &&
(passwd != "") ) {
QSqlDatabase *db;
QString protocol;
QString hostName;
QString dbName;
QString port;
// Open the Database Driver
parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);
if("odbc" == protocol)
db = QSqlDatabase::addDatabase("QODBC3");
else
db = QSqlDatabase::addDatabase("QPSQL7");
if (!db)
{
printf("Could not load the specified database driver.\n");
exit(-1);
}
// Try to connect to the Database
bool valport = FALSE;
int iport = port.toInt(&valport);
//.........这里部分代码省略.........
示例10: capabilitiesReplyFinished
void QgsWfsCapabilities::capabilitiesReplyFinished()
{
const QByteArray& buffer = mResponse;
QgsDebugMsg( "parsing capabilities: " + buffer );
// parse XML
QString capabilitiesDocError;
QDomDocument capabilitiesDocument;
if ( !capabilitiesDocument.setContent( buffer, true, &capabilitiesDocError ) )
{
mErrorCode = QgsWfsRequest::XmlError;
mErrorMessage = capabilitiesDocError;
emit gotCapabilities();
return;
}
QDomElement doc = capabilitiesDocument.documentElement();
// handle exceptions
if ( doc.tagName() == "ExceptionReport" )
{
QDomNode ex = doc.firstChild();
QString exc = ex.toElement().attribute( "exceptionCode", "Exception" );
QDomElement ext = ex.firstChild().toElement();
mErrorCode = QgsWfsRequest::ServerExceptionError;
mErrorMessage = exc + ": " + ext.firstChild().nodeValue();
emit gotCapabilities();
return;
}
mCaps.clear();
//test wfs version
mCaps.version = doc.attribute( "version" );
if ( !mCaps.version.startsWith( "1.0" ) &&
!mCaps.version.startsWith( "1.1" ) &&
!mCaps.version.startsWith( "2.0" ) )
{
mErrorCode = WFSVersionNotSupported;
mErrorMessage = tr( "WFS version %1 not supported" ).arg( mCaps.version );
emit gotCapabilities();
return;
}
// WFS 2.0 implementation are supposed to implement resultType=hits, and some
// implementations (GeoServer) might advertize it, whereas others (MapServer) do not.
// WFS 1.1 implementation too I think, but in the examples of the GetCapabilites
// response of the WFS 1.1 standard (and in common implementations), this is
// explictly advertized
if ( mCaps.version.startsWith( "2.0" ) )
mCaps.supportsHits = true;
// Note: for conveniency, we do not use the elementsByTagNameNS() method as
// the WFS and OWS namespaces URI are not the same in all versions
// find <ows:OperationsMetadata>
QDomElement operationsMetadataElem = doc.firstChildElement( "OperationsMetadata" );
if ( !operationsMetadataElem.isNull() )
{
QDomNodeList contraintList = operationsMetadataElem.elementsByTagName( "Constraint" );
for ( int i = 0; i < contraintList.size(); ++i )
{
QDomElement contraint = contraintList.at( i ).toElement();
if ( contraint.attribute( "name" ) == "DefaultMaxFeatures" /* WFS 1.1 */ )
{
QDomElement value = contraint.firstChildElement( "Value" );
if ( !value.isNull() )
{
mCaps.maxFeatures = value.text().toInt();
QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
}
}
else if ( contraint.attribute( "name" ) == "CountDefault" /* WFS 2.0 (e.g. MapServer) */ )
{
QDomElement value = contraint.firstChildElement( "DefaultValue" );
if ( !value.isNull() )
{
mCaps.maxFeatures = value.text().toInt();
QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
}
}
else if ( contraint.attribute( "name" ) == "ImplementsResultPaging" /* WFS 2.0 */ )
{
QDomElement value = contraint.firstChildElement( "DefaultValue" );
if ( !value.isNull() && value.text() == "TRUE" )
{
mCaps.supportsPaging = true;
QgsDebugMsg( "Supports paging" );
}
}
else if ( contraint.attribute( "name" ) == "ImplementsStandardJoins" ||
contraint.attribute( "name" ) == "ImplementsSpatialJoins" /* WFS 2.0 */ )
{
QDomElement value = contraint.firstChildElement( "DefaultValue" );
if ( !value.isNull() && value.text() == "TRUE" )
{
mCaps.supportsJoins = true;
QgsDebugMsg( "Supports joins" );
}
//.........这里部分代码省略.........
示例11: parcer
void QWeather::parcer(QDomDocument doc)
{
qDebug() << "parcer";
QDomElement root = doc.documentElement();
QDomNode n = root.firstChild();
n = root.firstChild();
n = n.firstChild();
while(!n.isNull())
{
QDomElement e = n.toElement();
if(!e.isNull())
{
if(e.tagName() == "yweather:location")
{
city = e.attribute("city", "");
region = e.attribute("region", "");
country = e.attribute("country", "");
}
else if(e.tagName() == "yweather:wind")
{
temperature = e.attribute("chill", "");
}
else if(e.tagName() == "yweather:atmosphere")
{
humidity = e.attribute("humidity", "");
pressure = e.attribute("pressure", "");
}
else if(e.tagName() == "item")
{
n = n.firstChild();
while(!n.isNull())
{
QDomElement e = n.toElement();
if(!e.isNull())
{
if(e.tagName() == "yweather:condition")
{
condition = e.attribute("text", "");
today_code = e.attribute("code", "");
temperature = e.attribute("temp","");
qDebug() << today_code;
}
if(e.tagName() == "yweather:forecast")
{
tomorrow_day = e.attribute("day","");
temperature_tomorrow_low = e.attribute("low","");
temperature_tomorrow_high = e.attribute("high","");
temperature_tomorrow_condition = e.attribute("text","");
tomorrow_code = e.attribute("code","");
n = n.nextSibling();
QDomElement e = n.toElement();
if(e.tagName() == "yweather:forecast")
{
d_a_t = e.attribute("day","");
d_a_t_low = e.attribute("low","");
d_a_t_high = e.attribute("high","");
d_a_t_condition = e.attribute("text","");
d_a_t_code = e.attribute("code","");
}
}
}
n = n.nextSibling();
}
n = n.parentNode();
}
}
n = n.nextSibling();
}
}
示例12: save
void Doc_Test::save()
{
Doc doc(this, m_fixtureDefCache);
Scene* s = new Scene(&doc);
doc.addFunction(s);
Fixture* f1 = new Fixture(&doc);
f1->setName("One");
f1->setChannels(5);
f1->setAddress(0);
f1->setUniverse(0);
doc.addFixture(f1);
Chaser* c = new Chaser(&doc);
doc.addFunction(c);
Fixture* f2 = new Fixture(&doc);
f2->setName("Two");
f2->setChannels(10);
f2->setAddress(20);
f2->setUniverse(1);
doc.addFixture(f2);
Collection* o = new Collection(&doc);
doc.addFunction(o);
Fixture* f3 = new Fixture(&doc);
f3->setName("Three");
f3->setChannels(15);
f3->setAddress(40);
f3->setUniverse(2);
doc.addFixture(f3);
EFX* e = new EFX(&doc);
doc.addFunction(e);
QVERIFY(doc.isModified() == true);
QDomDocument document;
QDomElement root = document.createElement("TestRoot");
QVERIFY(doc.saveXML(&document, &root) == true);
unsigned int fixtures = 0, functions = 0, buses = 0;
QDomNode node = root.firstChild();
QVERIFY(node.toElement().tagName() == "Engine");
node = node.firstChild();
while (node.isNull() == false)
{
QDomElement tag = node.toElement();
if (tag.tagName() == "Fixture")
fixtures++;
else if (tag.tagName() == "Function")
functions++;
else if (tag.tagName() == "Bus")
buses++;
else
QFAIL(QString("Unexpected tag: %1")
.arg(tag.tagName()).toAscii());
node = node.nextSibling();
}
QVERIFY(fixtures == 3);
QVERIFY(functions == 4);
QVERIFY(buses == Bus::count());
/* Saving doesn't implicitly reset modified status */
QVERIFY(doc.isModified() == true);
}
示例13: sImport
void ImportWindow::sImport()
{
_log->append(tr("Import Started..."));
QListWidgetItem * item = 0;
QList<QListWidgetItem *> list = _reports->selectedItems();
for(int i = 0; i < list.count(); i++)
{
item = list.at(i);
QString xml_file = item->text();
QString report_name = QString::null;
QString report_desc = QString::null;
QString report_src = QString::null;
int report_grade = item->data(Qt::UserRole).toInt();
if(!xml_file.isEmpty())
{
QFile file(xml_file);
if(file.open(QIODevice::ReadOnly))
{
QDomDocument doc;
QString errMsg;
int errLine, errCol;
if(doc.setContent(&file, &errMsg, &errLine, &errCol))
{
QDomElement root = doc.documentElement();
if(root.tagName() == "report")
{
for(QDomNode n = root.firstChild();
!n.isNull(); n = n.nextSibling())
{
if(n.nodeName() == "name")
report_name = n.firstChild().nodeValue();
else if(n.nodeName() == "description")
report_desc = n.firstChild().nodeValue();
}
report_src = doc.toString();
if(!report_name.isEmpty())
{
QSqlQuery qry;
QSqlQuery query;
qry.prepare(getSqlFromTag("fmt09", QSqlDatabase::database().driverName())); // MANU
qry.bindValue(":report_name", report_name); // MANU
qry.bindValue(":report_grade", report_grade); // MANU
qry.exec();
if(qry.first())
{
// update
query.prepare(getSqlFromTag("fmt10", QSqlDatabase::database().driverName())); // MANU
query.bindValue(":report_desc", report_desc); // MANU
query.bindValue(":report_src", report_src); // MANU
query.bindValue(":report_id", qry.value(0)); // MANU
query.bindValue(":report_name", report_name); // MANU
}
else
{
// insert
query.prepare(getSqlFromTag("fmt11", QSqlDatabase::database().driverName())); // MANU
query.bindValue(":report_name", report_name); // MANU
query.bindValue(":report_desc", report_desc); // MANU
query.bindValue(":report_src", report_src); // MANU
query.bindValue(":report_grade", report_grade); // MANU
}
if(!query.exec())
{
QSqlError err = query.lastError();
_log->append(tr("<font color=red>The following error was encountered while trying to import %1 into the database:\n"
"\t%2\n\t%3\n</font>")
.arg(xml_file)
.arg(err.driverText())
.arg(err.databaseText()));
}
else
_log->append(tr("Import successful of %1").arg(xml_file));
}
else
_log->append(tr("<font color=orange>The document %1 does not have a report name defined\n</font>")
.arg(xml_file));
}
else
_log->append(tr("<font color=red>XML Document %1 does not have root node of report\n</font>")
.arg(xml_file));
}
else
_log->append(tr("<font color=red>Error parsing file %1: %2 on line %3 column %4\n</font>")
.arg(xml_file).arg(errMsg).arg(errLine).arg(errCol));
}
else
_log->append(tr("<font color=red>Could not open the specified file: %1\n</font>")
.arg(xml_file));
}
else
_log->append("<font color=red>Encountered and empty entry: No file name was given.\n</font>");
}
_log->append(tr("Import complete!\n\n\n"));
}
示例14: importUAVSettings
// Slot called by the menu manager on user action
void UAVSettingsImportExportFactory::importUAVSettings()
{
// ask for file name
QString fileName;
QString filters = tr("UAVObjects XML files (*.uav);; XML files (*.xml)");
fileName = QFileDialog::getOpenFileName(0, tr("Import UAV Settings"), "", filters);
if (fileName.isEmpty()) {
return;
}
// Now open the file
QFile file(fileName);
QDomDocument doc("UAVObjects");
file.open(QFile::ReadOnly | QFile::Text);
if (!doc.setContent(file.readAll())) {
QMessageBox msgBox;
msgBox.setText(tr("File Parsing Failed."));
msgBox.setInformativeText(tr("This file is not a correct XML file"));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.exec();
return;
}
file.close();
// find the root of settings subtree
emit importAboutToBegin();
qDebug() << "Import about to begin";
QDomElement root = doc.documentElement();
if (root.tagName() == "uavobjects") {
root = root.firstChildElement("settings");
}
if (root.isNull() || (root.tagName() != "settings")) {
QMessageBox msgBox;
msgBox.setText(tr("Wrong file contents"));
msgBox.setInformativeText(tr("This file does not contain correct UAVSettings"));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.exec();
return;
}
// We are now ok: setup the import summary dialog & update it as we
// go along.
ImportSummaryDialog swui((QWidget *)Core::ICore::instance()->mainWindow());
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
swui.show();
QDomNode node = root.firstChild();
while (!node.isNull()) {
QDomElement e = node.toElement();
if (e.tagName() == "object") {
// - Read each object
QString uavObjectName = e.attribute("name");
uint uavObjectID = e.attribute("id").toUInt(NULL, 16);
// Sanity Check:
UAVObject *obj = objManager->getObject(uavObjectName);
if (obj == NULL) {
// This object is unknown!
qDebug() << "Object unknown:" << uavObjectName << uavObjectID;
swui.addLine(uavObjectName, "Error (Object unknown)", false);
} else {
// - Update each field
// - Issue and "updated" command
bool error = false;
bool setError = false;
QDomNode field = node.firstChild();
while (!field.isNull()) {
QDomElement f = field.toElement();
if (f.tagName() == "field") {
UAVObjectField *uavfield = obj->getField(f.attribute("name"));
if (uavfield) {
QStringList list = f.attribute("values").split(",");
if (list.length() == 1) {
if (false == uavfield->checkValue(f.attribute("values"))) {
qDebug() << "checkValue returned false on: " << uavObjectName << f.attribute("values");
setError = true;
} else {
uavfield->setValue(f.attribute("values"));
}
} else {
// This is an enum:
int i = 0;
QStringList list = f.attribute("values").split(",");
foreach(QString element, list) {
if (false == uavfield->checkValue(element, i)) {
qDebug() << "checkValue(list) returned false on: " << uavObjectName << list;
setError = true;
} else {
uavfield->setValue(element, i);
}
i++;
}
}
} else {
error = true;
//.........这里部分代码省略.........
示例15: SendSOAPRequest
//.........这里部分代码省略.........
LOG(VB_UPNP, LOG_DEBUG,
QString("SOAPClient(%1) sending:\n %2").arg(url.toString()).arg(aBuffer.constData()));
QString sXml;
if (!GetMythDownloadManager()->postAuth(url.toString(), &aBuffer, NULL, NULL, &headers))
{
LOG(VB_GENERAL, LOG_ERR, QString("SOAPClient::SendSOAPRequest: request failed: %1")
.arg(url.toString()));
}
else
sXml = QString(aBuffer);
// --------------------------------------------------------------
// Parse response
// --------------------------------------------------------------
LOG(VB_UPNP, LOG_DEBUG, "SOAPClient response:\n" +
QString("%1\n").arg(sXml));
// TODO handle timeout without response correctly.
list.clear();
QDomDocument doc;
if (!doc.setContent(sXml, true, &sErrDesc, &nErrCode))
{
LOG(VB_UPNP, LOG_ERR,
QString("SendSOAPRequest( %1 ) - Invalid response from %2")
.arg(sMethod).arg(url.toString()) +
QString("%1: %2").arg(nErrCode).arg(sErrDesc));
return xmlResult;
}
// --------------------------------------------------------------
// Is this a valid response?
// --------------------------------------------------------------
QString sResponseName = sMethod + "Response";
QDomNodeList oNodeList =
doc.elementsByTagNameNS(m_sNamespace, sResponseName);
if (oNodeList.count() == 0)
{
// --------------------------------------------------------------
// Must be a fault... parse it to return reason
// --------------------------------------------------------------
nErrCode = GetNodeValue(
doc, "Envelope/Body/Fault/detail/UPnPError/errorCode", 500);
sErrDesc = GetNodeValue(
doc, "Envelope/Body/Fault/detail/UPnPError/errorDescription", "");
if (sErrDesc.isEmpty())
sErrDesc = QString("Unknown #%1").arg(nErrCode);
QDomNode oNode = FindNode( "Envelope/Body/Fault", doc );
oNode = xmlResult.importNode( oNode, true );
xmlResult.appendChild( oNode );
return xmlResult;
}
QDomNode oMethod = oNodeList.item(0);
if (oMethod.isNull())
return xmlResult;
QDomNode oNode = oMethod.firstChild();
for (; !oNode.isNull(); oNode = oNode.nextSibling())
{
QDomElement e = oNode.toElement();
if (e.isNull())
continue;
QString sName = e.tagName();
QString sValue = "";
QDomText oText = oNode.firstChild().toText();
if (!oText.isNull())
sValue = oText.nodeValue();
list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
QUrl::fromPercentEncoding(sValue.toUtf8()));
}
// Create copy of oMethod that can be used with xmlResult.
oMethod = xmlResult.importNode( oMethod.firstChild(), true );
// importNode does not attach the new nodes to the document,
// do it here.
xmlResult.appendChild( oMethod );
return xmlResult;
}