QDomElement Task::makeTasksElement( QDomDocument document, const TaskList& tasks ) { QDomElement element = document.createElement( taskListTagName() ); Q_FOREACH( const Task& task, tasks ) { element.appendChild( task.toXml( document ) ); }
void QgsSOAPRequestHandler::setGetCapabilitiesResponse( const QDomDocument& doc ) { //Parse the QDomDocument Document and create a SOAP response QDomElement DocCapabilitiesElement = doc.firstChildElement(); if ( !DocCapabilitiesElement.isNull() ) { QDomNodeList capabilitiesNodes = DocCapabilitiesElement.elementsByTagName( "Capability" ); if ( capabilitiesNodes.size() > 0 ) { //create response document QDomDocument soapResponseDoc; //Envelope element QDomElement soapEnvelopeElement = soapResponseDoc.createElement( "soap:Envelope" ); soapEnvelopeElement.setAttribute( "xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/" ); soapEnvelopeElement.setAttribute( "soap:encoding", "http://schemas.xmlsoap.org/soap/encoding/" ); soapResponseDoc.appendChild( soapEnvelopeElement ); //Body element QDomElement soapBodyElement = soapResponseDoc.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "soap:Body" ); soapEnvelopeElement.appendChild( soapBodyElement ); // check if WMS or MS SOAP request if ( mService == "MS" || mService == "MDS" || mService == "MAS" ) { //OA_MI_MS_Capabilities element QDomElement msCapabilitiesElement = soapResponseDoc.createElement( "ms:OA_MI_Service_Capabilities" ); msCapabilitiesElement.setAttribute( "service", "MS" ); msCapabilitiesElement.setAttribute( "version", "1.1" ); msCapabilitiesElement.setAttribute( "xmlns:ms", "http://www.eu-orchestra.org/services/ms" ); msCapabilitiesElement.setAttribute( "xmlns", "http://www.eu-orchestra.org/services/oas/oa_basic" ); msCapabilitiesElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" ); msCapabilitiesElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); msCapabilitiesElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" ); soapBodyElement.appendChild( msCapabilitiesElement ); // import the orchestra common capabilities QFile common( "common.xml" ); if ( !common.open( QIODevice::ReadOnly ) ) { //throw an exception... QgsDebugMsg( "external orchestra common capabilities not found" ); } else { QDomDocument externCapDoc; QString parseError; int errorLineNo; if ( !externCapDoc.setContent( &common, false, &parseError, &errorLineNo ) ) { QgsDebugMsg( "parse error at setting content of external orchestra common capabilities: " + parseError + " at line " + QString::number( errorLineNo ) ); common.close(); } common.close(); // write common capabilities QDomElement orchestraCommon = externCapDoc.firstChildElement(); msCapabilitiesElement.appendChild( orchestraCommon ); // write specific capabilities QDomElement msSpecificCapabilitiesElement = soapResponseDoc.createElement( "serviceSpecificCapabilities" ); soapBodyElement.appendChild( msSpecificCapabilitiesElement ); QDomElement capabilitiesElement = capabilitiesNodes.item( 0 ).toElement(); msSpecificCapabilitiesElement.appendChild( capabilitiesElement ); // to do supportedOperations QDomNodeList requestNodes = capabilitiesElement.elementsByTagName( "Request" ); if ( requestNodes.size() > 0 ) { QDomElement requestElement = requestNodes.item( 0 ).toElement(); QDomNodeList requestChildNodes = requestElement.childNodes(); //append an array element for 'supportedOperations' to the soap document QDomElement supportedOperationsElement = soapResponseDoc.createElement( "supportedOperations" ); supportedOperationsElement.setAttribute( "xsi:type", "soapenc:Array" ); supportedOperationsElement.setAttribute( "soap:arrayType", "xsd:string[" + QString::number( requestChildNodes.size() ) + "]" ); for ( int i = 0; i < requestChildNodes.size(); ++i ) { QDomElement itemElement = soapResponseDoc.createElement( "item" ); QDomText itemText = soapResponseDoc.createTextNode( requestChildNodes.item( i ).toElement().tagName() ); itemElement.appendChild( itemText ); supportedOperationsElement.appendChild( itemElement ); } } //operationTypeInfo //predefinedLayers //predefinedDimensions //layerTypeInfo //predefinedStyles //supportedLayerDataInputFormat //supportedExceptionFormats //supportedDCP } } else if ( mService == "WMS" ) { //WMS_Capabilities element QDomElement msCapabilitiesElement = soapResponseDoc.createElement( "wms:Capabilities" ); msCapabilitiesElement.setAttribute( "service", "WMS" ); msCapabilitiesElement.setAttribute( "version", "1.3.0" ); msCapabilitiesElement.setAttribute( "xmlns:wms", "http://www.opengis.net/wms" ); msCapabilitiesElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" ); msCapabilitiesElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); msCapabilitiesElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" ); soapBodyElement.appendChild( msCapabilitiesElement ); QFile wmsService( "wms_metadata.xml" ); if ( !wmsService.open( QIODevice::ReadOnly ) ) { //throw an exception... QgsDebugMsg( "external wms service capabilities not found" ); } else { QDomDocument externServiceDoc; QString parseError; int errorLineNo; if ( !externServiceDoc.setContent( &wmsService, false, &parseError, &errorLineNo ) ) { QgsDebugMsg( "parse error at setting content of external wms service capabilities: " + parseError + " at line " + QString::number( errorLineNo ) ); wmsService.close(); } wmsService.close(); // write WMS Service capabilities QDomElement service = externServiceDoc.firstChildElement(); msCapabilitiesElement.appendChild( service ); } QDomElement msServiceElement = soapResponseDoc.createElement( "Service" ); msCapabilitiesElement.appendChild( msServiceElement ); QDomElement capabilitiesElement = capabilitiesNodes.item( 0 ).toElement(); msCapabilitiesElement.appendChild( capabilitiesElement ); } else { //OA_MI_MS_Capabilities element QDomElement msCapabilitiesElement = soapResponseDoc.createElement( "ms:OA_MI_Service_Capabilities" ); msCapabilitiesElement.setAttribute( "service", "MS" ); msCapabilitiesElement.setAttribute( "version", "1.1" ); msCapabilitiesElement.setAttribute( "xmlns:ms", "http://www.eu-orchestra.org/services/ms" ); msCapabilitiesElement.setAttribute( "xmlns", "http://www.eu-orchestra.org/services/oas/oa_basic" ); msCapabilitiesElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" ); msCapabilitiesElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); msCapabilitiesElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" ); soapBodyElement.appendChild( msCapabilitiesElement ); // import the orchestra common capabilities QFile common( "common.xml" ); if ( !common.open( QIODevice::ReadOnly ) ) { //throw an exception... QgsDebugMsg( "external orchestra common capabilities not found" ); } else { QDomDocument externCapDoc; QString parseError; int errorLineNo; if ( !externCapDoc.setContent( &common, false, &parseError, &errorLineNo ) ) { QgsDebugMsg( "parse error at setting content of external orchestra common capabilities: " + parseError + " at line " + QString::number( errorLineNo ) ); common.close(); } common.close(); // write common capabilities QDomElement orchestraCommon = externCapDoc.firstChildElement(); msCapabilitiesElement.appendChild( orchestraCommon ); } } QByteArray ba = soapResponseDoc.toByteArray(); setHttpResponse( &ba, "text/xml" ); } } }
bool QgsMapLayer::writeXML( QDomNode & layer_node, QDomDocument & document ) { // general layer metadata QDomElement maplayer = document.createElement( "maplayer" ); // use scale dependent visibility flag maplayer.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 ); maplayer.setAttribute( "minimumScale", minimumScale() ); maplayer.setAttribute( "maximumScale", maximumScale() ); // ID QDomElement layerId = document.createElement( "id" ); QDomText layerIdText = document.createTextNode( id() ); layerId.appendChild( layerIdText ); maplayer.appendChild( layerId ); // data source QDomElement dataSource = document.createElement( "datasource" ); QString src = source(); QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this ); if ( vlayer && vlayer->providerType() == "spatialite" ) { QgsDataSourceURI uri( src ); QString database = QgsProject::instance()->writePath( uri.database() ); uri.setConnection( uri.host(), uri.port(), database, uri.username(), uri.password() ); src = uri.uri(); } else if ( vlayer && vlayer->providerType() == "ogr" ) { QStringList theURIParts = src.split( "|" ); theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0] ); src = theURIParts.join( "|" ); } else if ( vlayer && vlayer->providerType() == "delimitedtext" ) { QUrl urlSource = QUrl::fromEncoded( src.toAscii() ); QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->writePath( urlSource.toLocalFile() ) ); urlDest.setQueryItems( urlSource.queryItems() ); src = QString::fromAscii( urlDest.toEncoded() ); } else { src = QgsProject::instance()->writePath( src ); } QDomText dataSourceText = document.createTextNode( src ); dataSource.appendChild( dataSourceText ); maplayer.appendChild( dataSource ); // layer name QDomElement layerName = document.createElement( "layername" ); QDomText layerNameText = document.createTextNode( name() ); layerName.appendChild( layerNameText ); maplayer.appendChild( layerName ); // timestamp if supported if ( timestamp() > QDateTime() ) { QDomElement stamp = document.createElement( "timestamp" ); QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) ); stamp.appendChild( stampText ); maplayer.appendChild( stamp ); } maplayer.appendChild( layerName ); // zorder // This is no longer stored in the project file. It is superfluous since the layers // are written and read in the proper order. // spatial reference system id QDomElement mySrsElement = document.createElement( "srs" ); mCRS->writeXML( mySrsElement, document ); maplayer.appendChild( mySrsElement ); // <transparencyLevelInt> QDomElement transparencyLevelIntElement = document.createElement( "transparencyLevelInt" ); QDomText transparencyLevelIntText = document.createTextNode( QString::number( getTransparency() ) ); transparencyLevelIntElement.appendChild( transparencyLevelIntText ); maplayer.appendChild( transparencyLevelIntElement ); // now append layer node to map layer node layer_node.appendChild( maplayer ); writeCustomProperties( maplayer, document ); return writeXml( maplayer, document ); } // bool QgsMapLayer::writeXML
void XmlCndInterface::writeCondition( QDomDocument doc, QDomElement &listTag, const FEMCondition* cond, const QString &condText, const QString &geometryName) const { QString geoName (QString::fromStdString(cond->getAssociatedGeometryName())); if ((geometryName.length()>0) && (geoName.compare(geometryName) != 0)) { std::cout << "Geometry name not matching, skipping condition \"" << cond->getGeoName() << "\"..." << std::endl; return; } QDomElement condTag ( doc.createElement(condText) ); condTag.setAttribute("geometry", geoName); listTag.appendChild(condTag); QDomElement processTag ( doc.createElement("Process") ); condTag.appendChild(processTag); QDomElement processTypeTag ( doc.createElement("Type") ); processTag.appendChild(processTypeTag); QDomText processTypeText ( doc.createTextNode( QString::fromStdString(FiniteElement::convertProcessTypeToString(cond->getProcessType()))) ); processTypeTag.appendChild(processTypeText); QDomElement processPVTag ( doc.createElement("Variable") ); processTag.appendChild(processPVTag); QDomText processPVText ( doc.createTextNode( QString::fromStdString(FiniteElement::convertPrimaryVariableToString(cond->getProcessPrimaryVariable()))) ); processPVTag.appendChild(processPVText); QDomElement geoTag ( doc.createElement("Geometry") ); condTag.appendChild(geoTag); QDomElement geoTypeTag ( doc.createElement("Type") ); geoTag.appendChild(geoTypeTag); QDomText geoTypeText ( doc.createTextNode( QString::fromStdString(GeoLib::convertGeoTypeToString(cond->getGeoType()))) ); geoTypeTag.appendChild(geoTypeText); QDomElement geoNameTag ( doc.createElement("Name") ); geoTag.appendChild(geoNameTag); QString geo_obj_name ( QString::fromStdString(cond->getGeoName()) ); QDomText geoNameText ( doc.createTextNode(geo_obj_name) ); geoNameTag.appendChild(geoNameText); QDomElement disTag ( doc.createElement("Distribution") ); condTag.appendChild(disTag); QDomElement disTypeTag ( doc.createElement("Type") ); disTag.appendChild(disTypeTag); QDomText disTypeText ( doc.createTextNode( QString::fromStdString(FiniteElement::convertDisTypeToString(cond->getProcessDistributionType()))) ); disTypeTag.appendChild(disTypeText); QDomElement disValueTag ( doc.createElement("Value") ); disTag.appendChild(disValueTag); /* if (cond->getProcessDistributionType() != FiniteElement::DIRECT) { double dis_value (cond->getDisValue()[0]); //TODO: do this correctly! disValueText = doc.createTextNode(QString::number(dis_value)); } else disValueText = doc.createTextNode(QString::fromStdString(cond->getDirectFileName())); */ const std::vector<size_t> dis_nodes = cond->getDisNodes(); const std::vector<double> dis_values = cond->getDisValues(); const size_t nNodes = dis_nodes.size(); const size_t nValues = dis_values.size(); std::stringstream ss; if (nNodes==0 && nValues==1) // CONSTANT ss << dis_values[0]; else if ((nValues>0) && (nValues==nNodes)) // LINEAR && DIRECT { ss << "\n\t"; for (size_t i=0; i<nValues; i++) ss << dis_nodes[i] << "\t" << dis_values[i] << "\n\t"; } else { std::cout << "Error in XmlCndInterface::writeCondition() - Inconsistent length of distribution value array." << std::endl; ss << "-9999"; } std::string dv = ss.str(); QDomText disValueText = doc.createTextNode(QString::fromStdString(ss.str())); disValueTag.appendChild(disValueText); }
/*! \overload */ void QFormatScheme::save(QDomElement& elem) const { QDomDocument doc = elem.ownerDocument(); elem.setAttribute("version", QFORMAT_VERSION); for ( int i = 0; i < m_formatKeys.count(); ++i ) { QDomText t; QDomElement f, c = doc.createElement("format"); c.setAttribute("id", m_formatKeys.at(i)); const QFormat& fmt = m_formatValues.at(i); f = doc.createElement("bold"); t = doc.createTextNode((fmt.weight == QFont::Bold) ? "true" : "false"); f.appendChild(t); c.appendChild(f); f = doc.createElement("italic"); t = doc.createTextNode(fmt.italic ? "true" : "false"); f.appendChild(t); c.appendChild(f); f = doc.createElement("overline"); t = doc.createTextNode(fmt.overline ? "true" : "false"); f.appendChild(t); c.appendChild(f); f = doc.createElement("underline"); t = doc.createTextNode(fmt.underline ? "true" : "false"); f.appendChild(t); c.appendChild(f); f = doc.createElement("strikeout"); t = doc.createTextNode(fmt.strikeout ? "true" : "false"); f.appendChild(t); c.appendChild(f); f = doc.createElement("waveUnderline"); t = doc.createTextNode(fmt.waveUnderline ? "true" : "false"); f.appendChild(t); c.appendChild(f); if ( fmt.foreground.isValid() ) { f = doc.createElement("foreground"); t = doc.createTextNode(fmt.foreground.name()); f.appendChild(t); c.appendChild(f); } if ( fmt.background.isValid() ) { f = doc.createElement("background"); t = doc.createTextNode(fmt.background.name()); f.appendChild(t); c.appendChild(f); } if ( fmt.linescolor.isValid() ) { f = doc.createElement("linescolor"); t = doc.createTextNode(fmt.linescolor.name()); f.appendChild(t); c.appendChild(f); } elem.appendChild(c); } }
void addToXML(QString data) { /* This fuction will parse the data from the CSPro into XML nodes. There are several controling bool variables to knows where in the CSPro data data is and how is its parent */ bool section; section = false; QString currData; currData = data; if (data == "[Dictionary]") { section = true; inDict = true; inLevel = false; inIdItems = false; inItem = false; inRecord = false; inValueSet = false; createRecords = true; dict = doc.createElement("Dictionary"); root.appendChild(dict); } if (data == "[Level]") { section = true; inDict = false; inLevel = true; inIdItems = false; inRecord = false; inItem = false; inValueSet = false; level = doc.createElement("Level"); dict.appendChild(level); } if (data == "[IdItems]") { section = true; inDict = false; inLevel = false; inIdItems = true; inRecord = false; inItem = false; inValueSet = false; createItems = true; iditems = doc.createElement("IdItems"); dict.appendChild(iditems); } if (data == "[Item]") { section = true; inDict = false; inLevel = false; inItem = true; inValueSet = false; if (createItems) { if (inIdItems) { items = doc.createElement("Items"); iditems.appendChild(items); } if (inRecord) { items = doc.createElement("Items"); record.appendChild(items); } createItems = false; } item = doc.createElement("Item"); items.appendChild(item); } if (data == "[Record]") { section = true; inDict = false; inLevel = false; inIdItems = false; inItem = false; inRecord = true; inValueSet = false; createItems = true; if (createRecords) { records = doc.createElement("Records"); dict.appendChild(records); createRecords = false; } record = doc.createElement("Record"); records.appendChild(record); } if (data == "[ValueSet]") { section = true; inDict = false; inLevel = false; inItem = false; inValueSet = true; valueSet = doc.createElement("ValueSet"); item.appendChild(valueSet); createValues = true; } if (section == false) { if (!inValueSet) { if (inDict) { appendVar(dict,data); } if (inLevel) { appendVar(level,data); } if ((inIdItems) && (!inItem)) { appendVar(iditems,data); } if ((inIdItems) && (inItem)) { appendVar(item,data); } if ((inRecord) && (!inItem)) { appendVar(record,data); } if ((inRecord) && (inItem)) { appendVar(item,data); } } else { if (!data.contains("Value=")) appendVar(valueSet,data); else { if (createValues) { valueSetValues = doc.createElement("ValueSetValues"); valueSet.appendChild(valueSetValues); appendValue(valueSetValues,data); createValues = false; } else appendValue(valueSetValues,data); } } } }
QDomElement PMObject::serialize( QDomDocument& doc ) const { QDomElement e = doc.createElement( className( ).lower( ) ); serialize( e, doc ); return e; }
QString QgsMapLayer::saveSldStyle( const QString theURI, bool & theResultFlag ) { QDomDocument myDocument = QDomDocument(); QDomNode header = myDocument.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"" ); myDocument.appendChild( header ); // Create the root element QDomElement root = myDocument.createElementNS( "http://www.opengis.net/sld", "StyledLayerDescriptor" ); root.setAttribute( "version", "1.1.0" ); root.setAttribute( "xsi:schemaLocation", "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd" ); root.setAttribute( "xmlns:ogc", "http://www.opengis.net/ogc" ); root.setAttribute( "xmlns:se", "http://www.opengis.net/se" ); root.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); root.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); myDocument.appendChild( root ); // Create the NamedLayer element QDomElement namedLayerNode = myDocument.createElement( "NamedLayer" ); root.appendChild( namedLayerNode ); QString errorMsg; QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this ); if ( !vlayer ) { theResultFlag = false; return tr( "Could not save symbology because:\n%1" ).arg( "Non-vector layers not supported yet" ); } if ( !vlayer->writeSld( namedLayerNode, myDocument, errorMsg ) ) { theResultFlag = false; return tr( "Could not save symbology because:\n%1" ).arg( errorMsg ); } // check if the uri is a file or ends with .sld, // which indicates that it should become one QString filename; if ( vlayer->providerType() == "ogr" ) { QStringList theURIParts = theURI.split( "|" ); filename = theURIParts[0]; } else if ( vlayer->providerType() == "delimitedtext" ) { filename = QUrl::fromEncoded( theURI.toAscii() ).toLocalFile(); } else { filename = theURI; } QFileInfo myFileInfo( filename ); if ( myFileInfo.exists() || filename.endsWith( ".sld", Qt::CaseInsensitive ) ) { QFileInfo myDirInfo( myFileInfo.path() ); //excludes file name if ( !myDirInfo.isWritable() ) { return tr( "The directory containing your dataset needs to be writable!" ); } // now construct the file name for our .sld style file QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".sld"; QFile myFile( myFileName ); if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) ) { QTextStream myFileStream( &myFile ); // save as utf-8 with 2 spaces for indents myDocument.save( myFileStream, 2 ); myFile.close(); theResultFlag = true; return tr( "Created default style file as %1" ).arg( myFileName ); } } theResultFlag = false; return tr( "ERROR: Failed to created SLD style file as %1. Check file permissions and retry." ).arg( filename ); }
QDomElement PixmapItem::getXmlItem(QDomDocument xml ) { QDomElement pictureItem = xml.createElement( "CardPixmapItem"); QDomElement newElement = xml.createElement( "name"); QDomText text = xml.createTextNode(name); newElement.appendChild(text); pictureItem.appendChild(newElement); newElement = xml.createElement( "source"); text = xml.createTextNode(QString::number(source)); newElement.appendChild(text); pictureItem.appendChild(newElement); newElement = xml.createElement( "file"); if(file != "" && source == 0) text = xml.createTextNode(file); else { if(source == 0) text = xml.createTextNode(":/images/gadu.png"); else text = xml.createTextNode(""); } newElement.appendChild(text); pictureItem.appendChild(newElement); newElement = xml.createElement( "posX"); text = xml.createTextNode(QString::number(pos().x())); newElement.appendChild(text); pictureItem.appendChild(newElement); newElement = xml.createElement( "posY"); text = xml.createTextNode(QString::number(pos().y())); newElement.appendChild(text); pictureItem.appendChild(newElement); newElement = xml.createElement( "zValue"); text = xml.createTextNode(QString::number( zValue() )); newElement.appendChild(text); pictureItem.appendChild(newElement); newElement = xml.createElement( "width"); text = xml.createTextNode(QString::number(boundingRect().width())); newElement.appendChild(text); pictureItem.appendChild(newElement); newElement = xml.createElement( "height"); text = xml.createTextNode(QString::number(boundingRect().height())); newElement.appendChild(text); pictureItem.appendChild(newElement); newElement = xml.createElement( "isLocked"); text = xml.createTextNode(QString::number(isLocked)); newElement.appendChild(text); pictureItem.appendChild(newElement); return pictureItem; }
void QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QDomDocument& doc, const QString& service, bool sia2045 ) const { QDomElement propertiesElement = propertiesElem(); if ( propertiesElement.isNull() ) { QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc ); return; } QDomElement serviceElem = doc.createElement( "Service" ); QDomElement serviceCapabilityElem = propertiesElement.firstChildElement( "WMSServiceCapabilities" ); if ( serviceCapabilityElem.isNull() || serviceCapabilityElem.text().compare( "true", Qt::CaseInsensitive ) != 0 ) { QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc ); return; } //Service name QDomElement wmsNameElem = doc.createElement( "Name" ); QDomText wmsNameText = doc.createTextNode( service ); wmsNameElem.appendChild( wmsNameText ); serviceElem.appendChild( wmsNameElem ); //WMS title //why not use project title ? QDomElement titleElem = propertiesElement.firstChildElement( "WMSServiceTitle" ); if ( !titleElem.isNull() ) { QDomElement wmsTitleElem = doc.createElement( "Title" ); QDomText wmsTitleText = doc.createTextNode( titleElem.text() ); wmsTitleElem.appendChild( wmsTitleText ); serviceElem.appendChild( wmsTitleElem ); } //WMS abstract QDomElement abstractElem = propertiesElement.firstChildElement( "WMSServiceAbstract" ); if ( !abstractElem.isNull() ) { QDomElement wmsAbstractElem = doc.createElement( "Abstract" ); QDomText wmsAbstractText = doc.createTextNode( abstractElem.text() ); wmsAbstractElem.appendChild( wmsAbstractText ); serviceElem.appendChild( wmsAbstractElem ); } //keyword list QDomElement keywordListElem = propertiesElement.firstChildElement( "WMSKeywordList" ); if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) { QDomElement wmsKeywordElem = doc.createElement( "KeywordList" ); //add default keyword QDomElement keywordElem = doc.createElement( "Keyword" ); keywordElem.setAttribute( "vocabulary", "ISO" ); QDomText keywordText = doc.createTextNode( "infoMapAccessService" ); /* If WFS and WCS 2.0 is implemented if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 ) keywordText = doc.createTextNode( "infoFeatureAccessService" ); else if ( service.compare( "WCS", Qt::CaseInsensitive ) == 0 ) keywordText = doc.createTextNode( "infoCoverageAccessService" );*/ keywordElem.appendChild( keywordText ); wmsKeywordElem.appendChild( keywordElem ); serviceElem.appendChild( wmsKeywordElem ); //add config keywords if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() ) { QDomNodeList keywordList = keywordListElem.elementsByTagName( "value" ); for ( int i = 0; i < keywordList.size(); ++i ) { keywordElem = doc.createElement( "Keyword" ); keywordText = doc.createTextNode( keywordList.at( i ).toElement().text() ); keywordElem.appendChild( keywordText ); if ( sia2045 ) { keywordElem.setAttribute( "vocabulary", "SIA_Geo405" ); } wmsKeywordElem.appendChild( keywordElem ); } } } else if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() ) { QDomNodeList keywordNodeList = keywordListElem.elementsByTagName( "value" ); QStringList keywordList; for ( int i = 0; i < keywordNodeList.size(); ++i ) { keywordList.push_back( keywordNodeList.at( i ).toElement().text() ); } QDomElement wmsKeywordElem = doc.createElement( "Keywords" ); if ( service.compare( "WCS", Qt::CaseInsensitive ) == 0 ) wmsKeywordElem = doc.createElement( "keywords" ); QDomText keywordText = doc.createTextNode( keywordList.join( ", " ) ); wmsKeywordElem.appendChild( keywordText ); serviceElem.appendChild( wmsKeywordElem ); } //OnlineResource element is mandatory according to the WMS specification QDomElement wmsOnlineResourceElem = propertiesElement.firstChildElement( "WMSOnlineResource" ); if ( !wmsOnlineResourceElem.isNull() ) { QDomElement onlineResourceElem = doc.createElement( "OnlineResource" ); if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 ) { QDomText onlineResourceText = doc.createTextNode( wmsOnlineResourceElem.text() ); onlineResourceElem.appendChild( onlineResourceText ); } else { onlineResourceElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); onlineResourceElem.setAttribute( "xlink:type", "simple" ); onlineResourceElem.setAttribute( "xlink:href", wmsOnlineResourceElem.text() ); } serviceElem.appendChild( onlineResourceElem ); } if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) //no contact information in WFS 1.0 and WCS 1.0 { //Contact information QDomElement contactInfoElem = doc.createElement( "ContactInformation" ); //Contact person primary QDomElement contactPersonPrimaryElem = doc.createElement( "ContactPersonPrimary" ); //Contact person QDomElement contactPersonElem = propertiesElement.firstChildElement( "WMSContactPerson" ); QString contactPersonString; if ( !contactPersonElem.isNull() ) { contactPersonString = contactPersonElem.text(); } QDomElement wmsContactPersonElem = doc.createElement( "ContactPerson" ); QDomText contactPersonText = doc.createTextNode( contactPersonString ); wmsContactPersonElem.appendChild( contactPersonText ); contactPersonPrimaryElem.appendChild( wmsContactPersonElem ); //Contact organisation QDomElement contactOrganizationElem = propertiesElement.firstChildElement( "WMSContactOrganization" ); QString contactOrganizationString; if ( !contactOrganizationElem.isNull() ) { contactOrganizationString = contactOrganizationElem.text(); } QDomElement wmsContactOrganizationElem = doc.createElement( "ContactOrganization" ); QDomText contactOrganizationText = doc.createTextNode( contactOrganizationString ); wmsContactOrganizationElem.appendChild( contactOrganizationText ); contactPersonPrimaryElem.appendChild( wmsContactOrganizationElem ); //Contact position QDomElement contactPositionElem = propertiesElement.firstChildElement( "WMSContactPosition" ); QString contactPositionString; if ( !contactPositionElem.isNull() ) { contactPositionString = contactPositionElem.text(); } QDomElement wmsContactPositionElem = doc.createElement( "ContactPosition" ); QDomText contactPositionText = doc.createTextNode( contactPositionString ); wmsContactPositionElem.appendChild( contactPositionText ); contactPersonPrimaryElem.appendChild( wmsContactPositionElem ); contactInfoElem.appendChild( contactPersonPrimaryElem ); //phone QDomElement phoneElem = propertiesElement.firstChildElement( "WMSContactPhone" ); if ( !phoneElem.isNull() ) { QDomElement wmsPhoneElem = doc.createElement( "ContactVoiceTelephone" ); QDomText wmsPhoneText = doc.createTextNode( phoneElem.text() ); wmsPhoneElem.appendChild( wmsPhoneText ); contactInfoElem.appendChild( wmsPhoneElem ); } //mail QDomElement mailElem = propertiesElement.firstChildElement( "WMSContactMail" ); if ( !mailElem.isNull() ) { QDomElement wmsMailElem = doc.createElement( "ContactElectronicMailAddress" ); QDomText wmsMailText = doc.createTextNode( mailElem.text() ); wmsMailElem.appendChild( wmsMailText ); contactInfoElem.appendChild( wmsMailElem ); } serviceElem.appendChild( contactInfoElem ); } //Fees QDomElement feesElem = propertiesElement.firstChildElement( "WMSFees" ); QDomElement wmsFeesElem = doc.createElement( "Fees" ); QDomText wmsFeesText = doc.createTextNode( "conditions unknown" ); // default value if access conditions are unknown if ( !feesElem.isNull() && !feesElem.text().isEmpty() ) { wmsFeesText = doc.createTextNode( feesElem.text() ); } wmsFeesElem.appendChild( wmsFeesText ); serviceElem.appendChild( wmsFeesElem ); //AccessConstraints QDomElement accessConstraintsElem = propertiesElement.firstChildElement( "WMSAccessConstraints" ); QDomElement wmsAccessConstraintsElem = doc.createElement( "AccessConstraints" ); QDomText wmsAccessConstraintsText = doc.createTextNode( "None" ); // default value if access constraints are unknown if ( !accessConstraintsElem.isNull() && !accessConstraintsElem.text().isEmpty() ) { wmsAccessConstraintsText = doc.createTextNode( accessConstraintsElem.text() ); } wmsAccessConstraintsElem.appendChild( wmsAccessConstraintsText ); serviceElem.appendChild( wmsAccessConstraintsElem ); //max width, max height for WMS if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) { QString version = doc.documentElement().attribute( "version" ); if ( version != "1.1.1" ) { //max width QDomElement mwElem = propertiesElement.firstChildElement( "WMSMaxWidth" ); if ( !mwElem.isNull() ) { QDomElement maxWidthElem = doc.createElement( "MaxWidth" ); QDomText maxWidthText = doc.createTextNode( mwElem.text() ); maxWidthElem.appendChild( maxWidthText ); serviceElem.appendChild( maxWidthElem ); } //max height QDomElement mhElem = propertiesElement.firstChildElement( "WMSMaxHeight" ); if ( !mhElem.isNull() ) { QDomElement maxHeightElem = doc.createElement( "MaxHeight" ); QDomText maxHeightText = doc.createTextNode( mhElem.text() ); maxHeightElem.appendChild( maxHeightText ); serviceElem.appendChild( maxHeightElem ); } } } parentElement.appendChild( serviceElem ); }
/** * Adds a QDomElement for the station to the element stationsElements (it will have the tags station) * @param doc XML Document * @param stationsElement */ void NMGStation::addXMLStationNode( QDomDocument& doc, QDomElement& stationsElement ) { QDomElement element = doc.createElement( TAG_STATION ); stationsElement.appendChild( element ); /* test host info */ QDomElement test = doc.createElement( TAG_STATION_TEST ); element.appendChild( test ); QDomElement testAddr = doc.createElement( TAG_STATION_ADDRESS ); test.appendChild( testAddr ); QDomText testAddrText = doc.createTextNode( getTestHost().getAddress() ); testAddr.appendChild( testAddrText ); if ( !getTestHost().getAlias().isEmpty() ) { QDomElement testAlias = doc.createElement( TAG_STATION_ALIAS ); test.appendChild( testAlias ); QDomText testAliasText = doc.createTextNode( getTestHost().getAlias() ); testAlias.appendChild( testAliasText ); } QDomElement testProtocol = doc.createElement( TAG_STATION_PROTOCOL ); test.appendChild( testProtocol ); QDomText testProtocolText = doc.createTextNode( getTestHost().isHostIPv4() ? STATION_PROTOCOL_IPV4 : STATION_PROTOCOL_IPV6 ); testProtocol.appendChild( testProtocolText ); /* management host info */ QDomElement management = doc.createElement( TAG_STATION_MANAGEMENT ); element.appendChild( management ); QDomElement managementAddr = doc.createElement( TAG_STATION_ADDRESS ); management.appendChild( managementAddr ); QDomText managementAddrText = doc.createTextNode( getManagementHost().getAddress() ); managementAddr.appendChild( managementAddrText ); QDomElement managementPort = doc.createElement( TAG_STATION_PORT ); management.appendChild( managementPort ); QDomText managementPortText = doc.createTextNode( QString::number(getManagementAddressPort()) ); managementPort.appendChild( managementPortText ); if ( !getManagementHost().getAlias().isEmpty() ) { QDomElement managementAlias = doc.createElement( TAG_STATION_ALIAS ); management.appendChild( managementAlias ); QDomText managementAliasText = doc.createTextNode( getManagementHost().getAlias() ); managementAlias.appendChild( managementAliasText ); } QDomElement managementProtocol = doc.createElement( TAG_STATION_PROTOCOL ); management.appendChild( managementProtocol ); QDomText managementProtocolText = doc.createTextNode( getManagementHost().isHostIPv4() ? STATION_PROTOCOL_IPV4 : STATION_PROTOCOL_IPV6 ); managementProtocol.appendChild( managementProtocolText ); QDomElement username = doc.createElement( TAG_STATION_USERNAME ); management.appendChild( username ); QDomText usernameText = doc.createTextNode( getManagementUsername() ); username.appendChild( usernameText ); ////B64 encrypted password!!! QDomElement password = doc.createElement( TAG_STATION_PASSWORD ); management.appendChild( password ); //QDomText passwordText = doc.createTextNode ( getManagementPassword() ); QByteArray b64pass (managementPassword.toUtf8()); QDomText passwordText = doc.createTextNode ( QString(b64pass.toBase64()) ); password.appendChild( passwordText ); /* Save fields to XML */ stationFieldsManager.addFieldNodetoXML( doc, element ); }
void FlpImport::processPluginParams( FL_Channel * _ch ) { qDebug( "plugin params for plugin %d (%d bytes): ", _ch->pluginType, _ch->pluginSettingsLength ); dump_mem( _ch->pluginSettings, _ch->pluginSettingsLength ); switch( _ch->pluginType ) { case FL_Plugin::Sampler: // AudioFileProcessor loaded { QDomDocument dd; QDomElement de = dd.createElement( _ch->instrumentPlugin->nodeName() ); de.setAttribute( "reversed", _ch->sampleReversed ); de.setAttribute( "amp", _ch->sampleAmp ); de.setAttribute( "looped", _ch->sampleUseLoopPoints ); de.setAttribute( "sframe", 0 ); de.setAttribute( "eframe", 1 ); de.setAttribute( "src", _ch->sampleFileName ); _ch->instrumentPlugin->restoreState( de ); break; } case FL_Plugin::TS404: // LB302 loaded break; case FL_Plugin::Fruity_3x_Osc: // TripleOscillator loaded { const Oscillator::WaveShapes mapped_3xOsc_Shapes[] = { Oscillator::SineWave, Oscillator::TriangleWave, Oscillator::SquareWave, Oscillator::SawWave, Oscillator::SquareWave, // square-sin Oscillator::WhiteNoise, Oscillator::UserDefinedWave } ; QDomDocument dd; QDomElement de = dd.createElement( _ch->instrumentPlugin->nodeName() ); de.setAttribute( "modalgo1", Oscillator::SignalMix ); de.setAttribute( "modalgo2", Oscillator::SignalMix ); int ws = Oscillator::UserDefinedWave; for( int i = 0; i < 3; ++i ) { const int32_t * d = (const int32_t *) ( _ch->pluginSettings + i * 28 ); QString is = QString::number( i ); de.setAttribute( "vol" + is, QString::number( d[0] * 100 / ( 3 * 128 ) ) ); de.setAttribute( "pan" + is, QString::number( d[1] ) ); de.setAttribute( "coarse" + is, QString::number( d[3] ) ); de.setAttribute( "finel" + is, QString::number( d[4] - d[6] / 2 ) ); de.setAttribute( "finer" + is, QString::number( d[4] + d[6] / 2 ) ); de.setAttribute( "stphdetun" + is, QString::number( d[5] ) ); const int s = mapped_3xOsc_Shapes[d[2]]; de.setAttribute( "wavetype" + is, QString::number( s ) ); if( s != Oscillator::UserDefinedWave ) { ws = s; } } if( ws == Oscillator::UserDefinedWave ) { de.setAttribute( "wavetype0", Oscillator::SawWave ); } de.setAttribute( "vol0", QString::number( 100/2 ) ); // now apply the prepared plugin-state _ch->instrumentPlugin->restoreState( de ); break; } case FL_Plugin::Layer: // nothing to do break; case FL_Plugin::Plucked: // Vibed loaded // TODO: setup vibed-instrument break; case FL_Plugin::UnknownPlugin: default: qDebug( "handling of plugin params not implemented " "for current plugin\n" ); break; } }
void Doc_Test::save() { Scene* s = new Scene(m_doc); m_doc->addFunction(s); Fixture* f1 = new Fixture(m_doc); f1->setName("One"); f1->setChannels(5); f1->setAddress(0); f1->setUniverse(0); m_doc->addFixture(f1); Chaser* c = new Chaser(m_doc); m_doc->addFunction(c); Fixture* f2 = new Fixture(m_doc); f2->setName("Two"); f2->setChannels(10); f2->setAddress(20); f2->setUniverse(1); m_doc->addFixture(f2); Collection* o = new Collection(m_doc); m_doc->addFunction(o); Fixture* f3 = new Fixture(m_doc); f3->setName("Three"); f3->setChannels(15); f3->setAddress(40); f3->setUniverse(2); m_doc->addFixture(f3); EFX* e = new EFX(m_doc); m_doc->addFunction(e); FixtureGroup* grp = new FixtureGroup(m_doc); grp->setName("Group 1"); m_doc->addFixtureGroup(grp); grp = new FixtureGroup(m_doc); grp->setName("Group 2"); m_doc->addFixtureGroup(grp); QVERIFY(m_doc->isModified() == true); QDomDocument document; QDomElement root = document.createElement("TestRoot"); QVERIFY(m_doc->saveXML(&document, &root) == true); uint fixtures = 0, groups = 0, functions = 0; QDomNode node = root.firstChild(); QVERIFY(node.toElement().tagName() == "Engine"); // Merely tests that the start of each hierarchy is found from the XML document. // Their contents are tested individually in their own separate tests. 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() == "FixtureGroup") groups++; else if (tag.tagName() == "Bus") QFAIL("Bus tags should not be saved anymore!"); else QFAIL(QString("Unexpected tag: %1") .arg(tag.tagName()).toLatin1()); node = node.nextSibling(); } QVERIFY(fixtures == 3); QVERIFY(groups == 2); QVERIFY(functions == 4); /* Saving doesn't implicitly reset modified status */ QVERIFY(m_doc->isModified() == true); }
QDomElement MaiaObject::toXml(QVariant arg) { //dummy document QDomDocument doc; //value element, we need this in each case QDomElement tagValue = doc.createElement("value"); switch(arg.type()) { case QVariant::String: { QDomElement tagString = doc.createElement("string"); QDomText textString = doc.createTextNode(arg.toString()); tagValue.appendChild(tagString); tagString.appendChild(textString); return tagString; } case QVariant::Int: { QDomElement tagInt = doc.createElement("int"); QDomText textInt = doc.createTextNode(QString::number(arg.toInt())); tagValue.appendChild(tagInt); tagInt.appendChild(textInt); return tagValue; } case QVariant::Double: { QDomElement tagDouble = doc.createElement("double"); QDomText textDouble = doc.createTextNode(QString::number(arg.toDouble())); tagValue.appendChild(tagDouble); tagDouble.appendChild(textDouble); return tagValue; } case QVariant::Bool: { QString textValue = arg.toBool() ? "1" : "0"; QDomElement tag = doc.createElement("boolean"); QDomText text = doc.createTextNode(textValue); tagValue.appendChild(tag); tag.appendChild(text); return tagValue; } case QVariant::ByteArray: { QString textValue = arg.toByteArray().toBase64(); QDomElement tag = doc.createElement("base64"); QDomText text = doc.createTextNode(textValue); tagValue.appendChild(tag); tag.appendChild(text); return tagValue; } case QVariant::DateTime: { QString textValue = arg.toDateTime().toString("yyyyMMddThh:mm:ss"); QDomElement tag = doc.createElement("datetime.iso8601"); QDomText text = doc.createTextNode(textValue); tagValue.appendChild(tag); tag.appendChild(text); return tagValue; } case QVariant::List: { QDomElement tagArray = doc.createElement("array"); QDomElement tagData = doc.createElement("data"); tagArray.appendChild(tagData); tagValue.appendChild(tagArray); const QList<QVariant> args = arg.toList(); for(int i = 0; i < args.size(); ++i) { tagData.appendChild(toXml(args.at(i))); } return tagValue; } case QVariant::Map: { QDomElement tagStruct = doc.createElement("struct"); QDomElement member; QDomElement name; tagValue.appendChild(tagStruct); QMap<QString, QVariant> map = arg.toMap(); QMapIterator<QString, QVariant> i(map); while(i.hasNext()) { i.next(); member = doc.createElement("member"); name = doc.createElement("name"); // (key) -> name -> member -> struct tagStruct.appendChild(member); member.appendChild(name); name.appendChild(doc.createTextNode(i.key())); // add variables by recursion member.appendChild(toXml(i.value())); } return tagValue; } default: qDebug() << "Failed to marshal unknown variant type: " << arg.type() << endl; } return QDomElement(); //QString::null; }
//! [0] QDomDocument doc; QDomImplementation impl; // This will create the element, but the resulting XML document will // be invalid, because '~' is not a valid character in a tag name. impl.setInvalidDataPolicy(QDomImplementation::AcceptInvalidData); QDomElement elt1 = doc.createElement("foo~bar"); // This will create an element with the tag name "foobar". impl.setInvalidDataPolicy(QDomImplementation::DropInvalidData); QDomElement elt2 = doc.createElement("foo~bar"); // This will create a null element. impl.setInvalidDataPolicy(QDomImplementation::ReturnNullNode); QDomElement elt3 = doc.createElement("foo~bar"); //! [0] //! [1] QDomDocument d; d.setContent(someXML); QDomNode n = d.firstChild(); while (!n.isNull()) { if (n.isElement()) { QDomElement e = n.toElement(); cout << "Element name: " << e.tagName() << endl; break; } n = n.nextSibling(); }
QByteArray TcxFileReader::toByteArray(Context *context, const RideFile *ride, bool withAlt, bool withWatts, bool withHr, bool withCad) const { QDomText text; QDomDocument doc; QDomProcessingInstruction hdr = doc.createProcessingInstruction("xml","version=\"1.0\""); doc.appendChild(hdr); // pwx QDomElement tcx = doc.createElementNS("http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2", "TrainingCenterDatabase"); tcx.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); tcx.setAttribute("xsi:schemaLocation", "http://www.garmin.com/xmlschemas/ActivityExtension/v2 http://www.garmin.com/xmlschemas/ActivityExtensionv2.xsd http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd"); //tcx.setAttribute("version", "2.0"); doc.appendChild(tcx); // activities, we just serialise one ride QString sport = ride->getTag("Sport", "Biking"); if (sport == QObject::tr("Biking") || sport == QObject::tr("Cycling") || sport == QObject::tr("Cycle") || sport == QObject::tr("Bike")) { sport = "Biking"; } QDomElement activities = doc.createElement("Activities"); tcx.appendChild(activities); QDomElement activity = doc.createElement("Activity"); activity.setAttribute("Sport", sport); // was ride->getTag("Sport", "Biking") but must be Biking, Running or Other activities.appendChild(activity); // time QDomElement id = doc.createElement("Id"); text = doc.createTextNode(ride->startTime().toUTC().toString(Qt::ISODate)); id.appendChild(text); activity.appendChild(id); QDomElement lap = doc.createElement("Lap"); lap.setAttribute("StartTime", ride->startTime().toUTC().toString(Qt::ISODate)); activity.appendChild(lap); const char *metrics[] = { "total_distance", "workout_time", "total_work", "average_hr", "max_heartrate", "average_cad", "max_cadence", "average_power", "max_power", "max_speed", "average_speed", NULL }; QStringList worklist = QStringList(); for (int i=0; metrics[i];i++) worklist << metrics[i]; QHash<QString, RideMetricPtr> computed = RideMetric::computeMetrics(context, ride, context->athlete->zones(), context->athlete->hrZones(), worklist); QDomElement lap_time = doc.createElement("TotalTimeSeconds"); text = doc.createTextNode(QString("%1").arg(computed.value("workout_time")->value(true))); //text = doc.createTextNode(ride->dataPoints().last()->secs); lap_time.appendChild(text); lap.appendChild(lap_time); QDomElement lap_distance = doc.createElement("DistanceMeters"); text = doc.createTextNode(QString("%1").arg(1000*computed.value("total_distance")->value(true))); //text = doc.createTextNode(ride->dataPoints().last()->km); lap_distance.appendChild(text); lap.appendChild(lap_distance); QDomElement max_speed = doc.createElement("MaximumSpeed"); text = doc.createTextNode(QString("%1") .arg(computed.value("max_speed")->value(true) / 3.6)); max_speed.appendChild(text); lap.appendChild(max_speed); QDomElement lap_calories = doc.createElement("Calories"); text = doc.createTextNode(QString("%1").arg((int)computed.value("total_work")->value(true))); lap_calories.appendChild(text); lap.appendChild(lap_calories); QDomElement avg_heartrate = doc.createElement("AverageHeartRateBpm"); QDomElement value = doc.createElement("Value"); text = doc.createTextNode(QString("%1").arg((int)computed.value("average_hr")->value(true))); value.appendChild(text); avg_heartrate.appendChild(value); lap.appendChild(avg_heartrate); QDomElement max_heartrate = doc.createElement("MaximumHeartRateBpm"); value = doc.createElement("Value"); text = doc.createTextNode(QString("%1").arg((int)computed.value("max_heartrate")->value(true))); value.appendChild(text); max_heartrate.appendChild(value); lap.appendChild(max_heartrate); QDomElement lap_intensity = doc.createElement("Intensity"); text = doc.createTextNode("Active"); lap_intensity.appendChild(text); lap.appendChild(lap_intensity); QDomElement lap_triggerMethod = doc.createElement("TriggerMethod"); text = doc.createTextNode("Manual"); lap_triggerMethod.appendChild(text); lap.appendChild(lap_triggerMethod); // samples // data points: timeoffset, dist, hr, spd, pwr, torq, cad, lat, lon, alt if (!ride->dataPoints().empty()) { QDomElement track = doc.createElement("Track"); lap.appendChild(track); foreach (const RideFilePoint *point, ride->dataPoints()) { QDomElement trackpoint = doc.createElement("Trackpoint"); track.appendChild(trackpoint); // time QDomElement time = doc.createElement("Time"); text = doc.createTextNode(ride->startTime().toUTC().addSecs(point->secs).toString(Qt::ISODate)); time.appendChild(text); trackpoint.appendChild(time); // position if (ride->areDataPresent()->lat && point->lat > -90.0 && point->lat < 90.0 && point->lat != 0.0 && ride->areDataPresent()->lon && point->lon > -180.00 && point->lon < 180.00 && point->lon != 0.0 ) { QDomElement position = doc.createElement("Position"); trackpoint.appendChild(position); // lat QDomElement lat = doc.createElement("LatitudeDegrees"); text = doc.createTextNode(QString("%1").arg(point->lat, 0, 'g', 11)); lat.appendChild(text); position.appendChild(lat); // lon QDomElement lon = doc.createElement("LongitudeDegrees"); text = doc.createTextNode(QString("%1").arg(point->lon, 0, 'g', 11)); lon.appendChild(text); position.appendChild(lon); } // alt if (withAlt && ride->areDataPresent()->alt && point->alt != 0.0) { QDomElement alt = doc.createElement("AltitudeMeters"); text = doc.createTextNode(QString("%1").arg(point->alt)); alt.appendChild(text); trackpoint.appendChild(alt); } // distance - meters if (ride->areDataPresent()->km) { QDomElement dist = doc.createElement("DistanceMeters"); text = doc.createTextNode(QString("%1").arg((int)(point->km*1000))); dist.appendChild(text); trackpoint.appendChild(dist); } if (withHr) { // HeartRate hack for Garmin Training Center // It needs an hr datapoint for every trackpoint or else the // hr graph in TC won't display. Schema defines the datapoint // as a positive int (> 0) int tHr = 1; if (ride->areDataPresent()->hr && point->hr >0.00) { tHr = (int)point->hr; } QDomElement hr = doc.createElement("HeartRateBpm"); hr.setAttribute("xsi:type", "HeartRateInBeatsPerMinute_t"); QDomElement value = doc.createElement("Value"); text = doc.createTextNode(QString("%1").arg(tHr)); value.appendChild(text); hr.appendChild(value); trackpoint.appendChild(hr); } // cad if (withCad && ride->areDataPresent()->cad && point->cad < 255) { //xsd maxInclusive value="254" QDomElement cad = doc.createElement("Cadence"); text = doc.createTextNode(QString("%1").arg((int)(point->cad))); cad.appendChild(text); trackpoint.appendChild(cad); } if (ride->areDataPresent()->kph || ride->areDataPresent()->watts) { QDomElement extension = doc.createElement("Extensions"); trackpoint.appendChild(extension); QDomElement tpx = doc.createElement("TPX"); tpx.setAttribute("xmlns", "http://www.garmin.com/xmlschemas/ActivityExtension/v2"); extension.appendChild(tpx); // spd - meters per second if (ride->areDataPresent()->kph) { QDomElement spd = doc.createElement("Speed"); text = doc.createTextNode(QString("%1").arg(point->kph / 3.6)); spd.appendChild(text); tpx.appendChild(spd); } // pwr if (withWatts && ride->areDataPresent()->watts) { QDomElement pwr = doc.createElement("Watts"); text = doc.createTextNode(QString("%1").arg((int)point->watts)); pwr.appendChild(text); tpx.appendChild(pwr); } } } }
int main(int argc, char *argv[]) { QString title; title = title + "****************************************************************** \n"; title = title + " * DictToXML 1.0 * \n"; title = title + " * This tool generates an XML structure of a CSPro dictionary * \n"; title = title + " * file. The XML has the same data as the DCF file but using * \n"; title = title + " * XML tags. The purpose of an XML structure is to easily read * \n"; title = title + " * dictionary information or to quickly alter value lists. * \n"; title = title + " * The XMLToDict do the oposite. * \n"; title = title + " * This tool is part of CSPro Tools (c) ILRI, 2012 * \n"; title = title + " ****************************************************************** \n"; TCLAP::CmdLine cmd(title.toLatin1().constData(), ' ', "1.0 (Beta 1)"); //Required arguments TCLAP::ValueArg<std::string> inputArg("i","input","Input CSPro DCF File",true,"","string"); TCLAP::ValueArg<std::string> outputArg("o","output","Output XML file. Default ./output.xml",false,"./output.xml","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()); QFile file(input); if (!file.exists()) { printLog("The input DCF file does not exits"); return 1; } if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { printLog("Cannot open DCF file"); return 1; } doc = QDomDocument("CSProXMLFile"); root = doc.createElement("CSProXML"); root.setAttribute("version", "1.0"); doc.appendChild(root); QTextStream in(&file); int pos; pos = 1; while (!in.atEnd()) { QString line = in.readLine(); if (!line.isEmpty()) addToXML(line); //Parse the line pos++; } if (createXML(output) != 0) { printLog("Error saving XML file"); return 1; } printLog("Done"); return 0; }
/** * Save the XMI representation of this object. */ void CodeClassFieldDeclarationBlock::saveToXMI(QDomDocument & doc, QDomElement & elem) { QDomElement docElement = doc.createElement(QLatin1String("ccfdeclarationcodeblock")); setAttributesOnNode(doc, docElement); elem.appendChild(docElement); }
QDomElement QgsGraduatedSymbolRendererV2::save( QDomDocument& doc ) { QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); rendererElem.setAttribute( "type", "graduatedSymbol" ); rendererElem.setAttribute( "symbollevels", ( mUsingSymbolLevels ? "1" : "0" ) ); rendererElem.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); rendererElem.setAttribute( "attr", mAttrName ); rendererElem.setAttribute( "graduatedMethod", graduatedMethodStr( mGraduatedMethod ) ); // ranges int i = 0; QgsSymbolV2Map symbols; QDomElement rangesElem = doc.createElement( "ranges" ); QgsRangeList::const_iterator it = mRanges.constBegin(); for ( ; it != mRanges.constEnd(); ++it ) { const QgsRendererRangeV2& range = *it; QString symbolName = QString::number( i ); symbols.insert( symbolName, range.symbol() ); QDomElement rangeElem = doc.createElement( "range" ); rangeElem.setAttribute( "lower", QString::number( range.lowerValue(), 'f' ) ); rangeElem.setAttribute( "upper", QString::number( range.upperValue(), 'f' ) ); rangeElem.setAttribute( "symbol", symbolName ); rangeElem.setAttribute( "label", range.label() ); rangeElem.setAttribute( "render", range.renderState() ? "true" : "false" ); rangesElem.appendChild( rangeElem ); i++; } rendererElem.appendChild( rangesElem ); // save symbols QDomElement symbolsElem = QgsSymbolLayerV2Utils::saveSymbols( symbols, "symbols", doc ); rendererElem.appendChild( symbolsElem ); // save source symbol if ( mSourceSymbol.data() ) { QgsSymbolV2Map sourceSymbols; sourceSymbols.insert( "0", mSourceSymbol.data() ); QDomElement sourceSymbolElem = QgsSymbolLayerV2Utils::saveSymbols( sourceSymbols, "source-symbol", doc ); rendererElem.appendChild( sourceSymbolElem ); } // save source color ramp if ( mSourceColorRamp.data() ) { QDomElement colorRampElem = QgsSymbolLayerV2Utils::saveColorRamp( "[source]", mSourceColorRamp.data(), doc ); rendererElem.appendChild( colorRampElem ); QDomElement invertedElem = doc.createElement( "invertedcolorramp" ); invertedElem.setAttribute( "value", mInvertedColorRamp ); rendererElem.appendChild( invertedElem ); } // save mode QString modeString; if ( mMode == EqualInterval ) modeString = "equal"; else if ( mMode == Quantile ) modeString = "quantile"; else if ( mMode == Jenks ) modeString = "jenks"; else if ( mMode == StdDev ) modeString = "stddev"; else if ( mMode == Pretty ) modeString = "pretty"; if ( !modeString.isEmpty() ) { QDomElement modeElem = doc.createElement( "mode" ); modeElem.setAttribute( "name", modeString ); rendererElem.appendChild( modeElem ); } QDomElement rotationElem = doc.createElement( "rotation" ); if ( mRotation.data() ) rotationElem.setAttribute( "field", QgsSymbolLayerV2Utils::fieldOrExpressionFromExpression( mRotation.data() ) ); rendererElem.appendChild( rotationElem ); QDomElement sizeScaleElem = doc.createElement( "sizescale" ); if ( mSizeScale.data() ) sizeScaleElem.setAttribute( "field", QgsSymbolLayerV2Utils::fieldOrExpressionFromExpression( mSizeScale.data() ) ); sizeScaleElem.setAttribute( "scalemethod", QgsSymbolLayerV2Utils::encodeScaleMethod( mScaleMethod ) ); rendererElem.appendChild( sizeScaleElem ); QDomElement labelFormatElem = doc.createElement( "labelformat" ); mLabelFormat.saveToDomElement( labelFormatElem ); rendererElem.appendChild( labelFormatElem ); if ( mPaintEffect && !QgsPaintEffectRegistry::isDefaultStack( mPaintEffect ) ) mPaintEffect->saveProperties( doc, rendererElem ); return rendererElem; }
void MyMoneyReport::writeXML ( QDomDocument& document, QDomElement& parent ) const { QDomElement el = document.createElement ( "REPORT" ); write ( el, &document, false ); parent.appendChild ( el ); }
void Config::addProfile(const Profile& p) { if (noConfig) { // Create XML tree from scratch. QDomDocument *doc = new QDomDocument(); QDomElement kap = doc->createElement("Kapture"); kap.setAttribute("xmlns", "http://kapture.berlios.de/config"); QDomElement classe = doc->createElement("xmppwin"); QDomElement prof = doc->createElement("profile"); prof.setAttribute("name", p.name()); QDomElement eJid = doc->createElement("jid"); QDomText vJid = doc->createTextNode(p.jid().full()); eJid.appendChild(vJid); QDomElement ePassword = doc->createElement("password"); QDomText vPassword = doc->createTextNode(p.password().toLatin1().toBase64()); ePassword.appendChild(vPassword); QDomElement eServer = doc->createElement("server"); QDomText vServer = doc->createTextNode(p.personnalServer()); eServer.appendChild(vServer); QDomElement ePort = doc->createElement("port"); QDomText vPort = doc->createTextNode(p.port()); ePort.appendChild(vPort); prof.appendChild(eJid); prof.appendChild(ePassword); prof.appendChild(eServer); prof.appendChild(ePort); classe.appendChild(prof); kap.appendChild(classe); doc->appendChild(kap); QFile *file = new QFile(QDir::homePath() + "/.Kapture/conf.xml"); file->open(QIODevice::WriteOnly); if (!file->exists()) { printf("An error occured while writing the file.\n"); return; // An error occured (QMessageBox) } file->write(doc->toByteArray(1)); delete file; } else { if (!xmppwinFound) { QDomElement classe = d.createElement("xmppwin"); //classes << classe; FIXME:there should be a way to do that (QList<QDomNode>) xmppwinN = classes.count() - 1; d.documentElement().appendChild(classe); xmppwinFound = true; } QDomElement prof = d.createElement("profile"); prof.setAttribute("name", p.name()); QDomElement eJid = d.createElement("jid"); QDomText vJid = d.createTextNode(p.jid().full()); eJid.appendChild(vJid); QDomElement ePassword = d.createElement("password"); QDomText vPassword = d.createTextNode(p.password().toLatin1().toBase64()); ePassword.appendChild(vPassword); QDomElement eServer = d.createElement("server"); QDomText vServer = d.createTextNode(p.personnalServer()); eServer.appendChild(vServer); QDomElement ePort = d.createElement("port"); QDomText vPort = d.createTextNode(p.port()); ePort.appendChild(vPort); prof.appendChild(eJid); prof.appendChild(ePassword); prof.appendChild(eServer); prof.appendChild(ePort); classes.at(xmppwinN).appendChild(prof); QFile *file = new QFile(QDir::homePath() + "/.Kapture/conf.xml"); file->open(QIODevice::WriteOnly); if (!file->exists()) { printf("An error occured while writing the file.\n"); return; // An error occured (QMessageBox) } file->write(d.toByteArray(1)); delete file; } }
void TestKHTML::setupActions() { QDomDocument document = m_part->domDocument(); QDomElement fileMenu = document.documentElement().firstChild().childNodes().item( 0 ).toElement(); QDomElement quitElement = document.createElement("action"); quitElement.setAttribute("name", KStandardAction::name(KStandardAction::Quit)); fileMenu.appendChild(quitElement); QDomElement viewMenu = document.documentElement().firstChild().childNodes().item( 2 ).toElement(); QDomElement element = document.createElement("action"); element.setAttribute("name", "debugRenderTree"); viewMenu.appendChild(element); element = document.createElement("action"); element.setAttribute("name", "debugDOMTree"); viewMenu.appendChild(element); QDomElement toolBar = document.documentElement().firstChild().nextSibling().toElement(); element = document.createElement("action"); element.setAttribute("name", "editable"); toolBar.insertBefore(element, toolBar.firstChild()); element = document.createElement("action"); element.setAttribute("name", "navigable"); toolBar.insertBefore(element, toolBar.firstChild()); element = document.createElement("action"); element.setAttribute("name", "reload"); toolBar.insertBefore(element, toolBar.firstChild()); element = document.createElement("action"); element.setAttribute("name", "print"); toolBar.insertBefore(element, toolBar.firstChild()); KAction *action = new KAction(KIcon("view-refresh"), "Reload", this ); m_part->actionCollection()->addAction( "reload", action ); connect(action, SIGNAL(triggered(bool)), this, SLOT(reload())); action->setShortcut(Qt::Key_F5); KAction *kprint = new KAction(KIcon("document-print"), "Print", this ); m_part->actionCollection()->addAction( "print", kprint ); connect(kprint, SIGNAL(triggered(bool)), m_part->browserExtension(), SLOT(print())); kprint->setEnabled(true); KToggleAction *ta = new KToggleAction( KIcon("edit-rename"), "Navigable", this ); actionCollection()->addAction( "navigable", ta ); ta->setShortcuts( KShortcut() ); ta->setChecked(m_part->isCaretMode()); connect(ta, SIGNAL(toggled(bool)), this, SLOT(toggleNavigable(bool))); ta = new KToggleAction( KIcon("document-properties"), "Editable", this ); actionCollection()->addAction( "editable", ta ); ta->setShortcuts( KShortcut() ); ta->setChecked(m_part->isEditable()); connect(ta, SIGNAL(toggled(bool)), this, SLOT(toggleEditable(bool))); KStandardAction::quit( kapp, SLOT(quit()), m_part->actionCollection() ); guiFactory()->addClient(m_part); }
/** @brief Enregistre les parametres dans un fichier de configuration xml */ bool ConfigXmlFile::save(const QString& filename,Configurable* config){ #ifdef _DEBUG QPRINT("save config <"+config->getConfigName()+"> to: "+filename); #endif QDomDocument doc; QFile f(filename); if(!f.open(QIODevice::ReadOnly)){ return QRESULT_DESC(Result::CantOpenFile,f.errorString()); } doc.setContent(&f); f.close(); // obtient noeud principale QDomElement root = doc.documentElement().firstChildElement(config->getConfigName()); //crée l'élément si il n'existe pas if(root.isNull()){ root = doc.createElement(config->getConfigName()); if(!root.isNull()) doc.documentElement().appendChild(root); } if(root.isNull()) return QRESULT_DESC(Result::CantEditXmlFile,"Création du noeud "+config->getConfigName()); //noeuds enfants ConfigParamList list; config->configRead(list); //scan les parametres for(ConfigParamList::const_iterator cur = list.begin(); cur != list.end(); cur++){ QString name = cur->first; // obtient noeud enfant QDomElement old_child = root.firstChildElement(name); //crée l'élément si il n'existe pas QDomElement child = doc.createElement(name); if(!child.isNull()) root.appendChild(child); if(child.isNull()) return QRESULT_DESC(Result::CantEditXmlFile,"Création du noeud "+name); //définit le texte QDomText text = doc.createTextNode(cur->second->getValue()); child.appendChild(text); //insert / remplace le nouveau noeud if(!old_child.isNull()) root.replaceChild(child,old_child); else root.appendChild(child); } //réouvre le fichier en écriture QTextStream sortie; f.setFileName(filename); if(!f.open(QIODevice::WriteOnly)){ return QRESULT_DESC(Result::CantOpenFile,f.errorString()); } sortie.setDevice(&f); // association du flux au fichier // insertion en début de document de <?xml version="1.0" ?> // QDomNode headNode = doc.createProcessingInstruction("xml","version=\"1.0\""); // doc.insertBefore(headNode, doc.firstChild()); // sauvegarde dans le flux (deux espaces de décalage dans l'arborescence) doc.save(sortie, 2); f.close(); return QRESULT_OK(); }
void QgsMarkerLineSymbolLayerV2::toSld( QDomDocument &doc, QDomElement &element, QgsStringMap props ) const { for ( int i = 0; i < mMarker->symbolLayerCount(); i++ ) { QDomElement symbolizerElem = doc.createElement( "se:LineSymbolizer" ); if ( !props.value( "uom", "" ).isEmpty() ) symbolizerElem.setAttribute( "uom", props.value( "uom", "" ) ); element.appendChild( symbolizerElem ); // <Geometry> QgsSymbolLayerV2Utils::createGeometryElement( doc, symbolizerElem, props.value( "geom", "" ) ); QString gap; switch ( mPlacement ) { case FirstVertex: symbolizerElem.appendChild( QgsSymbolLayerV2Utils::createVendorOptionElement( doc, "placement", "firstPoint" ) ); break; case LastVertex: symbolizerElem.appendChild( QgsSymbolLayerV2Utils::createVendorOptionElement( doc, "placement", "lastPoint" ) ); break; case CentralPoint: symbolizerElem.appendChild( QgsSymbolLayerV2Utils::createVendorOptionElement( doc, "placement", "centralPoint" ) ); break; case Vertex: // no way to get line/polygon's vertices, use a VendorOption symbolizerElem.appendChild( QgsSymbolLayerV2Utils::createVendorOptionElement( doc, "placement", "points" ) ); break; default: gap = QString::number( mInterval ); break; } if ( !mRotateMarker ) { // markers in LineSymbolizer must be drawn following the line orientation, // use a VendorOption when no marker rotation symbolizerElem.appendChild( QgsSymbolLayerV2Utils::createVendorOptionElement( doc, "rotateMarker", "0" ) ); } // <Stroke> QDomElement strokeElem = doc.createElement( "se:Stroke" ); symbolizerElem.appendChild( strokeElem ); // <GraphicStroke> QDomElement graphicStrokeElem = doc.createElement( "se:GraphicStroke" ); strokeElem.appendChild( graphicStrokeElem ); QgsSymbolLayerV2 *layer = mMarker->symbolLayer( i ); QgsMarkerSymbolLayerV2 *markerLayer = static_cast<QgsMarkerSymbolLayerV2 *>( layer ); if ( !markerLayer ) { graphicStrokeElem.appendChild( doc.createComment( QString( "MarkerSymbolLayerV2 expected, %1 found. Skip it." ).arg( markerLayer->layerType() ) ) ); } else { markerLayer->writeSldMarker( doc, graphicStrokeElem, props ); } if ( !gap.isEmpty() ) { QDomElement gapElem = doc.createElement( "se:Gap" ); QgsSymbolLayerV2Utils::createFunctionElement( doc, gapElem, gap ); graphicStrokeElem.appendChild( gapElem ); } if ( !qgsDoubleNear( mOffset, 0.0 ) ) { QDomElement perpOffsetElem = doc.createElement( "se:PerpendicularOffset" ); perpOffsetElem.appendChild( doc.createTextNode( QString::number( mOffset ) ) ); symbolizerElem.appendChild( perpOffsetElem ); } } }
QDomDocument M_PageSize::fopMeta() { QDomDocument dom; ////QString FopColor::foName( const QColor e ) FopColor hc = FopColor(); //// hc.foName( const QColor e ) QDomProcessingInstruction header = dom.createProcessingInstruction( "xml",QString("version=\"1.0\" encoding=\"utf-8\"" )); dom.appendChild( header ); //////QDateTime timer1( QDateTime::currentDateTime() ); /* time root */ QDomElement basexslforoot = dom.createElement("fo:root"); basexslforoot.setAttribute ("xmlns:fo","http://www.w3.org/1999/XSL/Format"); basexslforoot.setAttribute ("xmlns:svg","http://www.w3.org/2000/svg"); basexslforoot.setAttribute ("xmlns:cms","http://www.pulitzer.ch/2007/CMSFormat"); basexslforoot.setAttribute ("xmlns:fox","http://xmlgraphics.apache.org/fop/extensions"); dom.appendChild( basexslforoot ); const int blocks = 10; //////////// fox:outline QDomElement layout = dom.createElement("fo:layout-master-set"); layout.setAttribute ("writing-mode","lr-tb"); layout.setAttribute ("master-name","scribe"); basexslforoot.appendChild( layout ); QDomElement pmaster = dom.createElement("fo:simple-page-master"); pmaster.setAttribute ("master-name","scribe"); pmaster.setAttribute ("page-width",metrics(pageBoundingRect().width())); pmaster.setAttribute ("page-height",metrics(pageBoundingRect().height())); layout.appendChild( pmaster ); QDomElement rbody = dom.createElement("fo:region-body"); rbody.setAttribute ("region-name","xsl-region-body"); rbody.setAttribute ("background-color",hc.foName(body.bg)); rbody.setAttribute ("margin-top",metrics(body.margin_top)); rbody.setAttribute ("margin-bottom",metrics(body.margin_bottom)); rbody.setAttribute ("margin-left",metrics(body.margin_left)); rbody.setAttribute ("margin-right",metrics(body.margin_right)); if ( body.rpen.widthF() > 0 ) { /* make border */ ////rbody.setAttribute ("background-color",body.penString()); } pmaster.appendChild( rbody ); /* bookmark here .......... */ QDomElement bbtree = dom.createElement("fo:bookmark-tree"); QDomElement root_bookmark = dom.createElement("fo:bookmark"); bbtree.appendChild( root_bookmark); root_bookmark.setAttribute ("internal-destination","sec0"); QDomElement tree_a = dom.createElement("fo:bookmark-title"); tree_a .appendChild( dom.createTextNode ( "Internal dest.0" ) ); root_bookmark.appendChild( tree_a ); for (int i = 1; i < blocks; ++i) { QDomElement sub = dom.createElement("fo:bookmark"); sub.setAttribute ("internal-destination",QString("sec%1").arg(i)); QDomElement label= dom.createElement("fo:bookmark-title"); label.appendChild( dom.createTextNode ( QString("Internal dest.%1" ).arg(i) )); sub.appendChild( label ); root_bookmark.appendChild( sub ); } basexslforoot.appendChild( bbtree ); QDomElement rbefore = dom.createElement("fo:region-before"); rbefore.setAttribute ("region-name","xsl-region-before"); rbefore.setAttribute ("background-color",hc.foName(area[0].bg)); rbefore.setAttribute ("extent",metrics(body.margin_top)); pmaster.appendChild( rbefore ); /* pmaster.setAttribute ("margin-top",QString("%1pt").arg(body.margin_top)); pmaster.setAttribute ("margin-bottom",QString("%1pt").arg(body.margin_bottom)); pmaster.setAttribute ("margin-left",QString("%1pt").arg(body.margin_left)); pmaster.setAttribute ("margin-right",QString("%1pt").arg(body.margin_right)); */ QDomElement rafter = dom.createElement("fo:region-after"); rafter.setAttribute ("region-name","xsl-region-after"); rafter.setAttribute ("background-color",hc.foName(area[1].bg)); rafter.setAttribute ("extent",metrics(body.margin_bottom)); pmaster.appendChild( rafter ); QDomElement rstart = dom.createElement("fo:region-start"); rstart.setAttribute ("region-name","xsl-region-start"); rstart.setAttribute ("background-color",hc.foName(area[2].bg)); rstart.setAttribute ("extent",metrics(body.margin_left)); pmaster.appendChild( rstart ); QDomElement rend = dom.createElement("fo:region-end"); rend.setAttribute ("region-name","xsl-region-end"); rend.setAttribute ("background-color",hc.foName(area[3].bg)); rend.setAttribute ("extent",metrics(body.margin_right)); pmaster.appendChild( rend ); QDomElement pageseq1 = dom.createElement("fo:page-sequence"); pageseq1.setAttribute ("master-reference","scribe"); basexslforoot.appendChild( pageseq1 ); QDomElement txt_1 = dom.createElement("fo:static-content"); txt_1.setAttribute ("flow-name","xsl-region-before"); QDomElement a_txt_1 = dom.createElement("fo:block-container"); txt_1.appendChild( a_txt_1 ); QDomElement b_txt_1 = dom.createElement("fo:block"); b_txt_1.setAttribute ("color",hc.foName(area[0].bg)); b_txt_1.appendChild( dom.createTextNode ( "." ) ); a_txt_1.appendChild( b_txt_1 ); b_txt_1.appendChild( dom.createComment(QString("Header region / xsl-region-before ")) ); pageseq1.appendChild( txt_1 ); QDomElement txt_2 = dom.createElement("fo:static-content"); txt_2.setAttribute ("flow-name","xsl-region-after"); QDomElement a_txt_2 = dom.createElement("fo:block-container"); txt_2.appendChild( a_txt_2 ); QDomElement b_txt_2 = dom.createElement("fo:block"); b_txt_2.setAttribute ("color",hc.foName(area[1].bg)); b_txt_2.appendChild( dom.createTextNode ( "." ) ); a_txt_2.appendChild( b_txt_2 ); b_txt_2.appendChild( dom.createComment(QString("Footer region / xsl-region-after ")) ); pageseq1.appendChild( txt_2 ); QDomElement txt_3 = dom.createElement("fo:static-content"); txt_3.setAttribute ("flow-name","xsl-region-start"); QDomElement a_txt_3 = dom.createElement("fo:block-container"); txt_3.appendChild( a_txt_3 ); QDomElement b_txt_3 = dom.createElement("fo:block"); b_txt_3.setAttribute ("color",hc.foName(area[2].bg)); b_txt_3.appendChild( dom.createTextNode ( "." ) ); a_txt_3.appendChild( b_txt_3 ); b_txt_3.appendChild( dom.createComment(QString("Left region / xsl-region-start ")) ); pageseq1.appendChild( txt_3 ); QDomElement txt_4 = dom.createElement("fo:static-content"); txt_4.setAttribute ("flow-name","xsl-region-end"); QDomElement a_txt_4 = dom.createElement("fo:block-container"); txt_4.appendChild( a_txt_4 ); QDomElement b_txt_4 = dom.createElement("fo:block"); b_txt_4.setAttribute ("color",hc.foName(area[3].bg)); b_txt_4.appendChild( dom.createTextNode ( "." ) ); a_txt_4.appendChild( b_txt_4 ); b_txt_4.appendChild( dom.createComment(QString("Right region / xsl-region-end ")) ); pageseq1.appendChild( txt_4 ); QDomElement body = dom.createElement("fo:flow"); body.setAttribute ("flow-name","xsl-region-body"); body.appendChild( dom.createComment (QString("body blocks")) ); QDomElement sample = dom.createElement("fo:block"); sample.setAttribute ("break-after","page"); sample.setAttribute ("id",QString("sec0")); sample.setAttribute ("margin-top","2cm"); sample.appendChild( dom.createTextNode ( "Hello World! .........." ) ); body.appendChild( sample ); for (int i = 1; i < blocks; ++i) { QDomElement bloc = dom.createElement("fo:block"); bloc.setAttribute ("margin-top","2cm"); bloc.setAttribute ("id",QString("sec%1").arg(i)); bloc.setAttribute ("break-after","page"); bloc.appendChild( dom.createTextNode ( QString("Hello World nr.%1" ).arg(i) )); body.appendChild( bloc ); } pageseq1.appendChild( body ); //////////// body.appendChild( dom.createComment (QString("body blocks")) ); return dom; }
void QgsProjectFileTransform::convertRasterProperties( QDomDocument& doc, QDomNode& parentNode, QDomElement& rasterPropertiesElem, QgsRasterLayer* rlayer ) { QDomElement rasterRendererElem = doc.createElement( "rasterrenderer" ); //convert general properties //invert color rasterRendererElem.setAttribute( "invertColor", "0" ); QDomElement invertColorElem = rasterPropertiesElem.firstChildElement( "mInvertColor" ); if ( !invertColorElem.isNull() ) { if ( invertColorElem.text() == "true" ) { rasterRendererElem.setAttribute( "invertColor", "1" ); } } //opacity rasterRendererElem.setAttribute( "opacity", "1" ); QDomElement transparencyElem = parentNode.firstChildElement( "transparencyLevelInt" ); if ( !transparencyElem.isNull() ) { double transparency = transparencyElem.text().toInt(); rasterRendererElem.setAttribute( "opacity", QString::number( transparency / 255.0 ) ); } //alphaBand was not saved until now (bug) rasterRendererElem.setAttribute( "alphaBand", -1 ); //gray band is used for several renderers int grayBand = rasterBandNumber( rasterPropertiesElem, "mGrayBandName", rlayer ); //convert renderer specific properties QString drawingStyle = rasterPropertiesElem.firstChildElement( "mDrawingStyle" ).text(); if ( drawingStyle == "SingleBandGray" ) { rasterRendererElem.setAttribute( "type", "singlebandgray" ); rasterRendererElem.setAttribute( "grayBand", grayBand ); transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem ); } else if ( drawingStyle == "SingleBandPseudoColor" ) { rasterRendererElem.setAttribute( "type", "singlebandpseudocolor" ); rasterRendererElem.setAttribute( "band", grayBand ); QDomElement newRasterShaderElem = doc.createElement( "rastershader" ); QDomElement newColorRampShaderElem = doc.createElement( "colorrampshader" ); newRasterShaderElem.appendChild( newColorRampShaderElem ); rasterRendererElem.appendChild( newRasterShaderElem ); //switch depending on mColorShadingAlgorithm QString colorShadingAlgorithm = rasterPropertiesElem.firstChildElement( "mColorShadingAlgorithm" ).text(); if ( colorShadingAlgorithm == "PseudoColorShader" || colorShadingAlgorithm == "FreakOutShader" ) { newColorRampShaderElem.setAttribute( "colorRampType", "INTERPOLATED" ); //get minmax from rasterlayer QgsRasterBandStats rasterBandStats = rlayer->dataProvider()->bandStatistics( grayBand ); double minValue = rasterBandStats.minimumValue; double maxValue = rasterBandStats.maximumValue; double breakSize = ( maxValue - minValue ) / 3; QStringList colorList; if ( colorShadingAlgorithm == "FreakOutShader" ) { colorList << "#ff00ff" << "#00ffff" << "#ff0000" << "#00ff00"; } else //pseudocolor { colorList << "#0000ff" << "#00ffff" << "#ffff00" << "#ff0000"; } QStringList::const_iterator colorIt = colorList.constBegin(); double boundValue = minValue; for ( ; colorIt != colorList.constEnd(); ++colorIt ) { QDomElement newItemElem = doc.createElement( "item" ); newItemElem.setAttribute( "value", QString::number( boundValue ) ); newItemElem.setAttribute( "label", QString::number( boundValue ) ); newItemElem.setAttribute( "color", *colorIt ); newColorRampShaderElem.appendChild( newItemElem ); boundValue += breakSize; } } else if ( colorShadingAlgorithm == "ColorRampShader" ) { QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( "customColorRamp" ); QString type = customColorRampElem.firstChildElement( "colorRampType" ).text(); newColorRampShaderElem.setAttribute( "colorRampType", type ); QDomNodeList colorNodeList = customColorRampElem.elementsByTagName( "colorRampEntry" ); QString value, label; QColor newColor; int red, green, blue; QDomElement currentItemElem; for ( int i = 0; i < colorNodeList.size(); ++i ) { currentItemElem = colorNodeList.at( i ).toElement(); value = currentItemElem.attribute( "value" ); label = currentItemElem.attribute( "label" ); red = currentItemElem.attribute( "red" ).toInt(); green = currentItemElem.attribute( "green" ).toInt(); blue = currentItemElem.attribute( "blue" ).toInt(); newColor = QColor( red, green, blue ); QDomElement newItemElem = doc.createElement( "item" ); newItemElem.setAttribute( "value", value ); newItemElem.setAttribute( "label", label ); newItemElem.setAttribute( "color", newColor.name() ); newColorRampShaderElem.appendChild( newItemElem ); } } } else if ( drawingStyle == "PalettedColor" ) { rasterRendererElem.setAttribute( "type", "paletted" ); rasterRendererElem.setAttribute( "band", grayBand ); QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( "customColorRamp" ); QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( "colorRampEntry" ); QDomElement newColorPaletteElem = doc.createElement( "colorPalette" ); int red = 0; int green = 0; int blue = 0; int value = 0; QDomElement colorRampEntryElem; for ( int i = 0; i < colorRampEntryList.size(); ++i ) { colorRampEntryElem = colorRampEntryList.at( i ).toElement(); QDomElement newPaletteElem = doc.createElement( "paletteEntry" ); value = ( int )( colorRampEntryElem.attribute( "value" ).toDouble() ); newPaletteElem.setAttribute( "value", value ); red = colorRampEntryElem.attribute( "red" ).toInt(); green = colorRampEntryElem.attribute( "green" ).toInt(); blue = colorRampEntryElem.attribute( "blue" ).toInt(); newPaletteElem.setAttribute( "color", QColor( red, green, blue ).name() ); newColorPaletteElem.appendChild( newPaletteElem ); } rasterRendererElem.appendChild( newColorPaletteElem ); } else if ( drawingStyle == "MultiBandColor" ) { rasterRendererElem.setAttribute( "type", "multibandcolor" ); //red band, green band, blue band int redBand = rasterBandNumber( rasterPropertiesElem, "mRedBandName", rlayer ); int greenBand = rasterBandNumber( rasterPropertiesElem, "mGreenBandName", rlayer ); int blueBand = rasterBandNumber( rasterPropertiesElem, "mBlueBandName", rlayer ); rasterRendererElem.setAttribute( "redBand", redBand ); rasterRendererElem.setAttribute( "greenBand", greenBand ); rasterRendererElem.setAttribute( "blueBand", blueBand ); transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem ); } else { return; } //replace rasterproperties element with rasterrenderer element if ( !parentNode.isNull() ) { parentNode.replaceChild( rasterRendererElem, rasterPropertiesElem ); } }
int QgsSOAPRequestHandler::setUrlToFile( QImage* img ) { QString uri; QFile theFile; QDir tmpDir; QgsDebugMsg( "Entering." ); if ( findOutHostAddress( uri ) != 0 ) { return 1; } #ifdef WIN32 if ( !QFile::exists( QDir::currentPath() + "/tmp" ) ) { QDir::current().mkdir( "tmp" ); } tmpDir = QDir( QDir::currentPath() + "/tmp" ); #else //WIN32 tmpDir = QDir( "/tmp" ); #endif QgsDebugMsg( "Path to tmpDir is: " + tmpDir.absolutePath() ); //create a random folder under /tmp with map.jpg/png in it //and return the link to the client srand( time( NULL ) ); int randomNumber = rand(); QString folderName = QString::number( randomNumber ); if ( !QFile::exists( tmpDir.absolutePath() + "/mas_tmp" ) ) { QgsDebugMsg( "Trying to create mas_tmp folder" ); if ( !tmpDir.mkdir( "mas_tmp" ) ) { return 2; } } QDir tmpMasDir( tmpDir.absolutePath() + "/mas_tmp" ); if ( !tmpMasDir.mkdir( folderName ) ) { QgsDebugMsg( "Trying to create random folder" ); return 3; } QgsDebugMsg( "Temp. folder is: " + tmpMasDir.absolutePath() + "/" + folderName ); if ( mFormat == "JPG" ) { theFile.setFileName( tmpMasDir.absolutePath() + "/" + folderName + "/map.jpg" ); uri.append( "/mas_tmp/" + folderName + "/map.jpg" ); } else if ( mFormat == "PNG" ) { theFile.setFileName( tmpMasDir.absolutePath() + "/" + folderName + "/map.png" ); uri.append( "/mas_tmp/" + folderName + "/map.png" ); } if ( !theFile.open( QIODevice::WriteOnly ) ) { QgsDebugMsg( "Error, could not open file" ); return 4; } if ( !img->save( &theFile, mFormat.toLocal8Bit().data(), -1 ) ) { QgsDebugMsg( "Error, could not save image" ); return 5; } QDomDocument xmlResponse; QDomElement envelopeElement = xmlResponse.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "Envelope" ); xmlResponse.appendChild( envelopeElement ); QDomElement bodyElement = xmlResponse.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "Body" ); envelopeElement.appendChild( bodyElement ); QDomElement getMapResponseElement = xmlResponse.createElementNS( "http://www.eu-orchestra.org/services/ms", "getMapResponse" ); QDomElement ahrefElement = xmlResponse.createElement( "a" ); ahrefElement.setAttribute( "href", uri ); //QString href("<a href=\""+uri+"\">"+uri+"</a>"); QDomText uriNode = xmlResponse.createTextNode( uri ); ahrefElement.appendChild( uriNode ); //getMapResponseElement.appendChild(uriNode); getMapResponseElement.appendChild( ahrefElement ); bodyElement.appendChild( getMapResponseElement ); QByteArray xmlByteArray = xmlResponse.toByteArray(); setHttpResponse( &xmlByteArray, "text/xml" ); return 0; }
void QgsProjectFileTransform::transformContrastEnhancement( QDomDocument& doc, const QDomElement& rasterproperties, QDomElement& rendererElem ) { if ( rasterproperties.isNull() || rendererElem.isNull() ) { return; } double minimumValue = 0; double maximumValue = 0; QDomElement contrastMinMaxElem = rasterproperties.firstChildElement( "contrastEnhancementMinMaxValues" ); if ( contrastMinMaxElem.isNull() ) { return; } QDomElement contrastEnhancementAlgorithmElem = rasterproperties.firstChildElement( "mContrastEnhancementAlgorithm" ); if ( contrastEnhancementAlgorithmElem.isNull() ) { return; } //convert enhancement name to enumeration int algorithmEnum = 0; QString algorithmString = contrastEnhancementAlgorithmElem.text(); if ( algorithmString == "StretchToMinimumMaximum" ) { algorithmEnum = 1; } else if ( algorithmString == "StretchAndClipToMinimumMaximum" ) { algorithmEnum = 2; } else if ( algorithmString == "ClipToMinimumMaximum" ) { algorithmEnum = 3; } else if ( algorithmString == "UserDefinedEnhancement" ) { algorithmEnum = 4; } QDomNodeList minMaxEntryList = contrastMinMaxElem.elementsByTagName( "minMaxEntry" ); QStringList enhancementNameList; if ( minMaxEntryList.size() == 1 ) { enhancementNameList << "contrastEnhancement"; } if ( minMaxEntryList.size() == 3 ) { enhancementNameList << "redContrastEnhancement" << "greenContrastEnhancement" << "blueContrastEnhancement"; } if ( minMaxEntryList.size() > enhancementNameList.size() ) { return; } QDomElement minMaxEntryElem; for ( int i = 0; i < minMaxEntryList.size(); ++i ) { minMaxEntryElem = minMaxEntryList.at( i ).toElement(); QDomElement minElem = minMaxEntryElem.firstChildElement( "min" ); if ( minElem.isNull() ) { return; } minimumValue = minElem.text().toDouble(); QDomElement maxElem = minMaxEntryElem.firstChildElement( "max" ); if ( maxElem.isNull() ) { return; } maximumValue = maxElem.text().toDouble(); QDomElement newContrastEnhancementElem = doc.createElement( enhancementNameList.at( i ) ); QDomElement newMinValElem = doc.createElement( "minValue" ); QDomText minText = doc.createTextNode( QString::number( minimumValue ) ); newMinValElem.appendChild( minText ); newContrastEnhancementElem.appendChild( newMinValElem ); QDomElement newMaxValElem = doc.createElement( "maxValue" ); QDomText maxText = doc.createTextNode( QString::number( maximumValue ) ); newMaxValElem.appendChild( maxText ); newContrastEnhancementElem.appendChild( newMaxValElem ); QDomElement newAlgorithmElem = doc.createElement( "algorithm" ); QDomText newAlgorithmText = doc.createTextNode( QString::number( algorithmEnum ) ); newAlgorithmElem.appendChild( newAlgorithmText ); newContrastEnhancementElem.appendChild( newAlgorithmElem ); rendererElem.appendChild( newContrastEnhancementElem ); } }
void QgsProjectFileTransform::convertRasterProperties( QDomDocument& doc, QDomNode& parentNode, QDomElement& rasterPropertiesElem, QgsRasterLayer* rlayer ) { //no data //TODO: We would need to set no data on all bands, but we don't know number of bands here QDomNode noDataNode = rasterPropertiesElem.namedItem( QStringLiteral( "mNoDataValue" ) ); QDomElement noDataElement = noDataNode.toElement(); if ( !noDataElement.text().isEmpty() ) { QgsDebugMsg( "mNoDataValue = " + noDataElement.text() ); QDomElement noDataElem = doc.createElement( QStringLiteral( "noData" ) ); QDomElement noDataRangeList = doc.createElement( QStringLiteral( "noDataRangeList" ) ); noDataRangeList.setAttribute( QStringLiteral( "bandNo" ), 1 ); QDomElement noDataRange = doc.createElement( QStringLiteral( "noDataRange" ) ); noDataRange.setAttribute( QStringLiteral( "min" ), noDataElement.text() ); noDataRange.setAttribute( QStringLiteral( "max" ), noDataElement.text() ); noDataRangeList.appendChild( noDataRange ); noDataElem.appendChild( noDataRangeList ); parentNode.appendChild( noDataElem ); } QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterrenderer" ) ); //convert general properties //invert color rasterRendererElem.setAttribute( QStringLiteral( "invertColor" ), QStringLiteral( "0" ) ); QDomElement invertColorElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "mInvertColor" ) ); if ( !invertColorElem.isNull() ) { if ( invertColorElem.text() == QLatin1String( "true" ) ) { rasterRendererElem.setAttribute( QStringLiteral( "invertColor" ), QStringLiteral( "1" ) ); } } //opacity rasterRendererElem.setAttribute( QStringLiteral( "opacity" ), QStringLiteral( "1" ) ); QDomElement transparencyElem = parentNode.firstChildElement( QStringLiteral( "transparencyLevelInt" ) ); if ( !transparencyElem.isNull() ) { double transparency = transparencyElem.text().toInt(); rasterRendererElem.setAttribute( QStringLiteral( "opacity" ), QString::number( transparency / 255.0 ) ); } //alphaBand was not saved until now (bug) rasterRendererElem.setAttribute( QStringLiteral( "alphaBand" ), -1 ); //gray band is used for several renderers int grayBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mGrayBandName" ), rlayer ); //convert renderer specific properties QString drawingStyle = rasterPropertiesElem.firstChildElement( QStringLiteral( "mDrawingStyle" ) ).text(); // While PalettedColor should normally contain only integer values, usually // color palette 0-255, it may happen (Tim, issue #7023) that it contains // colormap classification with double values and text labels // (which should normally only appear in SingleBandPseudoColor drawingStyle) // => we have to check first the values and change drawingStyle if necessary if ( drawingStyle == QLatin1String( "PalettedColor" ) ) { QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) ); QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) ); for ( int i = 0; i < colorRampEntryList.size(); ++i ) { QDomElement colorRampEntryElem = colorRampEntryList.at( i ).toElement(); QString strValue = colorRampEntryElem.attribute( QStringLiteral( "value" ) ); double value = strValue.toDouble(); if ( value < 0 || value > 10000 || !qgsDoubleNear( value, static_cast< int >( value ) ) ) { QgsDebugMsg( QString( "forcing SingleBandPseudoColor value = %1" ).arg( value ) ); drawingStyle = QStringLiteral( "SingleBandPseudoColor" ); break; } } } if ( drawingStyle == QLatin1String( "SingleBandGray" ) ) { rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "singlebandgray" ) ); rasterRendererElem.setAttribute( QStringLiteral( "grayBand" ), grayBand ); transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem ); } else if ( drawingStyle == QLatin1String( "SingleBandPseudoColor" ) ) { rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "singlebandpseudocolor" ) ); rasterRendererElem.setAttribute( QStringLiteral( "band" ), grayBand ); QDomElement newRasterShaderElem = doc.createElement( QStringLiteral( "rastershader" ) ); QDomElement newColorRampShaderElem = doc.createElement( QStringLiteral( "colorrampshader" ) ); newRasterShaderElem.appendChild( newColorRampShaderElem ); rasterRendererElem.appendChild( newRasterShaderElem ); //switch depending on mColorShadingAlgorithm QString colorShadingAlgorithm = rasterPropertiesElem.firstChildElement( QStringLiteral( "mColorShadingAlgorithm" ) ).text(); if ( colorShadingAlgorithm == QLatin1String( "PseudoColorShader" ) || colorShadingAlgorithm == QLatin1String( "FreakOutShader" ) ) { newColorRampShaderElem.setAttribute( QStringLiteral( "colorRampType" ), QStringLiteral( "INTERPOLATED" ) ); //get minmax from rasterlayer QgsRasterBandStats rasterBandStats = rlayer->dataProvider()->bandStatistics( grayBand ); double minValue = rasterBandStats.minimumValue; double maxValue = rasterBandStats.maximumValue; double breakSize = ( maxValue - minValue ) / 3; QStringList colorList; if ( colorShadingAlgorithm == QLatin1String( "FreakOutShader" ) ) { colorList << QStringLiteral( "#ff00ff" ) << QStringLiteral( "#00ffff" ) << QStringLiteral( "#ff0000" ) << QStringLiteral( "#00ff00" ); } else //pseudocolor { colorList << QStringLiteral( "#0000ff" ) << QStringLiteral( "#00ffff" ) << QStringLiteral( "#ffff00" ) << QStringLiteral( "#ff0000" ); } QStringList::const_iterator colorIt = colorList.constBegin(); double boundValue = minValue; for ( ; colorIt != colorList.constEnd(); ++colorIt ) { QDomElement newItemElem = doc.createElement( QStringLiteral( "item" ) ); newItemElem.setAttribute( QStringLiteral( "value" ), QString::number( boundValue ) ); newItemElem.setAttribute( QStringLiteral( "label" ), QString::number( boundValue ) ); newItemElem.setAttribute( QStringLiteral( "color" ), *colorIt ); newColorRampShaderElem.appendChild( newItemElem ); boundValue += breakSize; } } else if ( colorShadingAlgorithm == QLatin1String( "ColorRampShader" ) ) { QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) ); QString type = customColorRampElem.firstChildElement( QStringLiteral( "colorRampType" ) ).text(); newColorRampShaderElem.setAttribute( QStringLiteral( "colorRampType" ), type ); QDomNodeList colorNodeList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) ); QString value, label; QColor newColor; int red, green, blue; QDomElement currentItemElem; for ( int i = 0; i < colorNodeList.size(); ++i ) { currentItemElem = colorNodeList.at( i ).toElement(); value = currentItemElem.attribute( QStringLiteral( "value" ) ); label = currentItemElem.attribute( QStringLiteral( "label" ) ); red = currentItemElem.attribute( QStringLiteral( "red" ) ).toInt(); green = currentItemElem.attribute( QStringLiteral( "green" ) ).toInt(); blue = currentItemElem.attribute( QStringLiteral( "blue" ) ).toInt(); newColor = QColor( red, green, blue ); QDomElement newItemElem = doc.createElement( QStringLiteral( "item" ) ); newItemElem.setAttribute( QStringLiteral( "value" ), value ); newItemElem.setAttribute( QStringLiteral( "label" ), label ); newItemElem.setAttribute( QStringLiteral( "color" ), newColor.name() ); newColorRampShaderElem.appendChild( newItemElem ); } } } else if ( drawingStyle == QLatin1String( "PalettedColor" ) ) { rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "paletted" ) ); rasterRendererElem.setAttribute( QStringLiteral( "band" ), grayBand ); QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) ); QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) ); QDomElement newColorPaletteElem = doc.createElement( QStringLiteral( "colorPalette" ) ); int red = 0; int green = 0; int blue = 0; int value = 0; QDomElement colorRampEntryElem; for ( int i = 0; i < colorRampEntryList.size(); ++i ) { colorRampEntryElem = colorRampEntryList.at( i ).toElement(); QDomElement newPaletteElem = doc.createElement( QStringLiteral( "paletteEntry" ) ); value = static_cast< int >( colorRampEntryElem.attribute( QStringLiteral( "value" ) ).toDouble() ); newPaletteElem.setAttribute( QStringLiteral( "value" ), value ); red = colorRampEntryElem.attribute( QStringLiteral( "red" ) ).toInt(); green = colorRampEntryElem.attribute( QStringLiteral( "green" ) ).toInt(); blue = colorRampEntryElem.attribute( QStringLiteral( "blue" ) ).toInt(); newPaletteElem.setAttribute( QStringLiteral( "color" ), QColor( red, green, blue ).name() ); QString label = colorRampEntryElem.attribute( QStringLiteral( "label" ) ); if ( !label.isEmpty() ) { newPaletteElem.setAttribute( QStringLiteral( "label" ), label ); } newColorPaletteElem.appendChild( newPaletteElem ); } rasterRendererElem.appendChild( newColorPaletteElem ); } else if ( drawingStyle == QLatin1String( "MultiBandColor" ) ) { rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "multibandcolor" ) ); //red band, green band, blue band int redBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mRedBandName" ), rlayer ); int greenBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mGreenBandName" ), rlayer ); int blueBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mBlueBandName" ), rlayer ); rasterRendererElem.setAttribute( QStringLiteral( "redBand" ), redBand ); rasterRendererElem.setAttribute( QStringLiteral( "greenBand" ), greenBand ); rasterRendererElem.setAttribute( QStringLiteral( "blueBand" ), blueBand ); transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem ); } else { return; } //replace rasterproperties element with rasterrenderer element if ( !parentNode.isNull() ) { parentNode.replaceChild( rasterRendererElem, rasterPropertiesElem ); } }
//create single day's database file bool createDB(QString date){ srand(time(NULL)); //define environmental variable for random function to select QString city[9] = {"Guangzhou","Shanghai","Beijing","Haerbin","Chengdu","Chongqing","HongKong","Dalian","Tianjin"}; QString planes[4] = {"A300","A310","A320","A340"}; QString cab[3][3] = {{"A","1","8"},{"B","0.7","30"},{"C","0.4","150"}}; //associate with data file, create XML file declaration and root element QFile file("Resources\\" + date + ".xml"); if(!file.open(QFile::WriteOnly | QFile::Text))return false; QDomDocument doc; QDomProcessingInstruction instruction; instruction = doc.createProcessingInstruction("xml","version=\"1.0\""); doc.appendChild(instruction); QDomElement root = doc.createElement("dateIndex"); doc.appendChild(root); //define tag reference QDomElement depCity; QDomElement arrCity; QDomElement flight; //QDomElement ID; //QDomElement depTime; //QDomElement arrTime; //QDomElement totalTime; //QDomElement plane; //QDomElement cabins; QDomElement cabin; //QDomElement price; //QDomElement quota; //QDomElement remain; //Loop to produce sub-elements for(int i = 0; i < 9; i ++){ depCity = doc.createElement("depCity"); depCity.setAttribute("name",city[i]); root.appendChild(depCity); for(int j = 0; j < 9; j ++){ if(city[i] == city[j])continue; //if repeated arrCity = doc.createElement("arrCity"); arrCity.setAttribute("name",city[j]); depCity.appendChild(arrCity); int totalt = rand() % 4 + 1; //travel duration for(int k = 0; k < 8; k ++){ int num = rand() % 9000 + 1000; //flight number int dept = 8 + k * 2; //departure time int arrt = (dept + totalt) % 25; //arrive time int pri = (rand() % 20) * 100 + 2000; //price of A cabin flight = doc.createElement("flight"); arrCity.appendChild(flight); flight.setAttribute("ID","CZ" + QString::number(num)); flight.setAttribute("depTime", QString::number(dept) + ":00"); flight.setAttribute("arrTime", QString::number(arrt) + ":00"); flight.setAttribute("totalTime", QString::number(totalt) + " hours"); flight.setAttribute("plane", planes[rand() % 4]); /* ID = doc.createElement("ID"); depTime = doc.createElement("depTime"); arrTime = doc.createElement("arrTime"); totalTime = doc.createElement("totalTime"); plane = doc.createElement("plane"); cabins = doc.createElement("cabins"); flight.appendChild(ID); flight.appendChild(depTime); flight.appendChild(arrTime); flight.appendChild(totalTime); flight.appendChild(plane); flight.appendChild(cabins); ID.appendChild(doc.createTextNode("CZ" + QString::number(num))); depTime.appendChild(doc.createTextNode(QString::number(dept) + ":00")); arrTime.appendChild(doc.createTextNode(QString::number(arrt) + ":00")); totalTime.appendChild(doc.createTextNode(QString::number(totalt) + " hours")); plane.appendChild(doc.createTextNode(planes[rand() % 4])); */ for(int m = 0; m < 3; m ++){ cabin = doc.createElement("cabin"); flight.appendChild(cabin); cabin.setAttribute("name", cab[m][0]); cabin.setAttribute("price", QString::number(int(pri * cab[m][1].toFloat()))); cabin.setAttribute("quota", cab[m][2]); cabin.setAttribute("remain", cab[m][2]); /* price = doc.createElement("price"); quota = doc.createElement("quota"); remain = doc.createElement("remain"); price.appendChild(doc.createTextNode(QString::number(int(pri * cab[l][1].toFloat())))); quota.appendChild(doc.createTextNode(cab[l][2])); remain.appendChild(doc.createTextNode(cab[l][2])); cabin.appendChild(price); cabin.appendChild(quota); cabin.appendChild(remain); */ } } } } //save the dom tree into xml file QTextStream out(&file); doc.save(out,4); file.close(); return true; }