void DialogEditNodeTable::LoadContent()
{
    //Load the element value
    m_pValueLine->setText(m_node.toElement().text());

    //Get all the attributes
    QDomNamedNodeMap attributes = m_node.attributes();

    m_pTable->setRowCount(attributes.size());

    QTableWidgetItem* item = 0;

    //Add each attribute in to the table
    for(int indexRow=0; indexRow < attributes.size(); ++indexRow)
    {
        int columnIndex = 0;

        QDomAttr attributeNode = attributes.item(indexRow).toAttr();

        item = new QTableWidgetItem(attributeNode.nodeName());// << attribute name
        item->setToolTip(attributeNode.nodeName());
        m_pTable->setItem(indexRow, columnIndex, item);
        columnIndex++;

        item = new QTableWidgetItem(attributeNode.nodeValue());// << value
        item->setToolTip(attributeNode.nodeValue());
        m_pTable->setItem(indexRow, columnIndex, item);
        columnIndex++;
    }

}
int QDomNamedNodeMapProto:: size() const
{
  QDomNamedNodeMap *item = qscriptvalue_cast<QDomNamedNodeMap*>(thisObject());
  if (item)
    return item->size();
  return 0;
}
Example #3
0
bool OsisData::ProcessAttributes(QDomElement& xmlElement)
{
   // Parse and save attributes
   QDomNamedNodeMap attr = xmlElement.attributes();
   int size = attr.size();
   if (!size)
   {
      return false; // Error
   }

   for (int i = 0; i < size; i++)
   {
      QDomAttr at = attr.item(i).toAttr();
      QString value(at.value());
      int key = getEnumKey("OsisElementAttributes", at.name().toLocal8Bit().constData());

      if (key != -1)
      {
         if (Attribute.contains(key))
         {
            Attribute.remove(key);
         }
         Attribute[key] = value;
      }
      else
      {
         qCritical() << "<" << ElementName << ">:  Unknown attribute: " << at.name() << "=" << value << endl;
      }
   }

   return true;
}
/** Construct an DrugDrugInteraction object using the XML QDomElement. */
DrugDrugInteraction::DrugDrugInteraction(const QDomElement &element)
{
    if (element.tagName()!="DDI") {
        LOG_ERROR_FOR("DrugDrugInteraction", "Wrong XML Element");
    } else {
        m_Data.insert(FirstInteractorName, Constants::correctedUid(Utils::removeAccents(element.attribute("i1"))));
        m_Data.insert(SecondInteractorName, Constants::correctedUid(Utils::removeAccents(element.attribute("i2"))));
        m_Data.insert(FirstInteractorRouteOfAdministrationIds, element.attribute("i1ra").split(";"));
        m_Data.insert(SecondInteractorRouteOfAdministrationIds, element.attribute("i2ra").split(";"));
        m_Data.insert(LevelCode, element.attribute("l"));
        m_Data.insert(LevelName, ::levelName(element.attribute("l")));
        m_Data.insert(DateCreation, QDate::fromString(element.attribute("a", QDate(2010,01,01).toString(Qt::ISODate)), Qt::ISODate));
        m_Data.insert(DateLastUpdate, QDate::fromString(element.attribute("lu", QDate(2010,01,01).toString(Qt::ISODate)), Qt::ISODate));
        m_Data.insert(IsValid, element.attribute("v", "1").toInt());
        m_Data.insert(IsReviewed, element.attribute("rv", "0").toInt());
        if (!element.attribute("p").isEmpty())
            m_Data.insert(PMIDsStringList, element.attribute("p").split(";"));
        m_Data.insert(IsDuplicated, false);
        // Read Risk
        QDomElement risk = element.firstChildElement("R");
        while (!risk.isNull()) {
            setRisk(risk.attribute("t"), risk.attribute("l"));
            risk = risk.nextSiblingElement("R");
        }
        // Read Management
        QDomElement management = element.firstChildElement("M");
        while (!management.isNull()) {
            setManagement(management.attribute("t"), management.attribute("l"));
            management = management.nextSiblingElement("M");
        }
        // Read Dose related interactions
        QDomElement dose = element.firstChildElement("D");
        while (!dose.isNull()) {
            DrugDrugInteractionDose *ddidose = 0;
            if (dose.attribute("i") == "1") {
                ddidose = &m_FirstDose;
            } else {
                ddidose = &m_SecondDose;
            }
            if (dose.attribute("uf").toInt()==1) {
                ddidose->setData(DrugDrugInteractionDose::UsesFrom, true);
                ddidose->setData(DrugDrugInteractionDose::FromValue , dose.attribute("fv"));
                ddidose->setData(DrugDrugInteractionDose::FromUnits, dose.attribute("fu"));
                ddidose->setData(DrugDrugInteractionDose::FromRepartition , dose.attribute("fr"));
            } else if (dose.attribute("ut").toInt()==1) {
                ddidose->setData(DrugDrugInteractionDose::UsesTo, true);
                ddidose->setData(DrugDrugInteractionDose::ToValue , dose.attribute("tv"));
                ddidose->setData(DrugDrugInteractionDose::ToUnits, dose.attribute("tu"));
                ddidose->setData(DrugDrugInteractionDose::ToRepartition , dose.attribute("tr"));
            }
            dose = dose.nextSiblingElement("D");
        }
        // Read formalized risk
        QDomElement form = element.firstChildElement("F");
        QDomNamedNodeMap attributeMap = form.attributes();
        for(int i=0; i < attributeMap.size(); ++i) {
            addFormalized(attributeMap.item(i).nodeName(), form.attribute(attributeMap.item(i).nodeName()));
        }
    }
}
Example #5
0
static void helperToXmlAddDomElement(QXmlStreamWriter* stream, const QDomElement& element, const QStringList &omitNamespaces)
{
    stream->writeStartElement(element.tagName());

    /* attributes */
    QString xmlns = element.namespaceURI();
    if (!xmlns.isEmpty() && !omitNamespaces.contains(xmlns))
        stream->writeAttribute("xmlns", xmlns);
    QDomNamedNodeMap attrs = element.attributes();
    for (int i = 0; i < attrs.size(); i++)
    {
        QDomAttr attr = attrs.item(i).toAttr();
        stream->writeAttribute(attr.name(), attr.value());
    }

    /* children */
    QDomNode childNode = element.firstChild();
    while (!childNode.isNull())
    {
        if (childNode.isElement())
        {
            helperToXmlAddDomElement(stream, childNode.toElement(), QStringList() << xmlns);
        } else if (childNode.isText()) {
            stream->writeCharacters(childNode.toText().data());
        }
        childNode = childNode.nextSibling();
    }
    stream->writeEndElement();
}
Example #6
0
void ViElement::fromDom(QDomNode &dom)
{
	setName(dom.toElement().tagName());
	QDomNamedNodeMap attributes = dom.attributes();
	for(int i = 0; i < attributes.size(); ++i)
	{
		addAttribute(ViAttribute(attributes.item(i).nodeName(), attributes.item(i).nodeValue()));
	}
	QDomNodeList children = dom.childNodes();
	if(children.size() > 0)
	{
		for(int i = 0; i < children.size(); ++i)
		{
			if(children.item(i).isText())
			{
				setValue(children.item(i).nodeValue());
			}
			else
			{
				ViElement child;
				QDomNode node = children.item(i);
				child.fromDom(node);
				addChild(child);
			}
		}
	}
	else
	{
		setValue(dom.nodeValue());
	}
}
QString QDomNamedNodeMapProto::toString() const
{
  QDomNamedNodeMap *item = qscriptvalue_cast<QDomNamedNodeMap*>(thisObject());
  if (item)
    return QString("[QDomNamedNodeMap(size = %1)]").arg(item->size());
  return QString("[QDomNamedNodeMap(unknown)]");
}
Example #8
0
inline void DefinitionParser::checkAttributes (QDomNode& node) const
{
	const QString tag = node.toElement().tagName();
	QDomNamedNodeMap attr = node.attributes();
	for (int i = 0; i < attr.size(); ++i) {
		QDomNode a = attr.item(i);
		if (!_attributesMap[a.nodeName()]) {
			warning("invalid attribute \'" + a.nodeName() + "\' in \'" + tag + "\'");
		}
	}
}
Example #9
0
void DebuggerTool::processNodeAttributes(const QDomElement &element)
{
    QDomNamedNodeMap namedNodeMap = element.attributes();

    for (int i = 0; i < namedNodeMap.size(); ++i) {
        QDomNode domNode = namedNodeMap.item(i);

        if (domNode.nodeType() == QDomNode::AttributeNode) {
            QDomAttr domElement = domNode.toAttr();
            m_anyAttribute.insert(domElement.name(), domElement.value());
//            vc_dbg << "Any AttributeNode: name: " << domElement.name() << " value: " << domElement.value();
        }
    }
}
/**
* \brief This function return the named attribute's value of a given element
* \author Jules Gorny - ALCoV team, ISIT, UMR 6284 UdA – CNRS
* \param doc : QDomDocument containing the xml tree
* \param elementName : element name
* \param attrName : attribute name
* \return the element attribute value or an empty character
*/
QString getElemAttributeValue(QDomDocument& doc, QString elementName, QString attrName)
{	
	QDomNodeList elements = doc.elementsByTagName(elementName);

	//If we find an element with the same name
	if( elements.size() == 1 )
	{
		QDomNamedNodeMap elemAttributes = elements.at(0).attributes();
		for(int j=0; j<elemAttributes.size(); j++)
		{
			QString atName = elemAttributes.item(j).toAttr().name();
			if( attrName == atName )
				return elemAttributes.item(j).toAttr().value();
		}
	}
	return "";
}
Example #11
0
void Platform::processNodeAttributes(const QDomElement &element)
{
    QDomNamedNodeMap namedNodeMap = element.attributes();

    if (namedNodeMap.size() == 1) {
        QDomNode domNode = namedNodeMap.item(0);

        if (domNode.nodeType() == QDomNode::AttributeNode) {
            QDomAttr domElement = domNode.toAttr();

            if (domElement.name() == QString("Name")) {
                m_name = domElement.value();
//                vc_dbg << "AttributeNode: name: " << domElement.name() << " value: " << domElement.value();
            }
        }
    }
}
Example #12
0
void Xml::htmlToString(QDomElement e, int level, QString* s)
      {
      *s += QString("<%1").arg(e.tagName());
      QDomNamedNodeMap map = e.attributes();
      int n = map.size();
      for (int i = 0; i < n; ++i) {
            QDomAttr a = map.item(i).toAttr();
            *s += QString(" %1=\"%2\"").arg(a.name()).arg(a.value());
            }
      *s += ">";
      ++level;
      for (QDomNode ee = e.firstChild(); !ee.isNull(); ee = ee.nextSibling()) {
            if (ee.nodeType() == QDomNode::ElementNode)
                  htmlToString(ee.toElement(), level, s);
            else if (ee.nodeType() == QDomNode::TextNode)
                  *s += Qt::escape(ee.toText().data());
            }
      *s += QString("</%1>").arg(e.tagName());
      --level;
      }
QVector<Value> AVRStudioXMLParser::GetValues(QDomNodeList nodelist)
{
    QVector<Value> values;

    for(int i = 0; i < nodelist.size(); i++)
    {
        QDomNamedNodeMap attributes =  nodelist.at(i).attributes();
        Value value;

        for(int i = 0; i < attributes.size(); i++)
        {
            QDomNode attribute = attributes.item(i);
            if(value.GetMappingMap()[attribute.nodeName()])
                *value.GetMappingMap()[attribute.nodeName()] = attribute.nodeValue();
        }

        values.append(value);
    }

    return values;
}
QVector<ProgrammingInterface> AVRStudioXMLParser::GetInterfaces(QDomNode node)
{
    QVector<ProgrammingInterface> interfaces(0);

    while(!node.isNull())
    {
        QDomNamedNodeMap attributes = node.attributes();
        ProgrammingInterface interface;

        for(int i = 0; i < attributes.size(); i++)
        {
            QDomNode attribute = attributes.item(i);
            if(interface.GetMappingMap()[attribute.nodeName()])
                *interface.GetMappingMap()[attribute.nodeName()] = attribute.nodeValue();
        }

        interfaces.append(interface);
        node = node.nextSibling();
    }

    return interfaces;
}
Example #15
0
void Project::processNodeAttributes(const QDomElement &nodeElement)
{
    // process attributes
    QDomNamedNodeMap namedNodeMap = nodeElement.attributes();

    for (int i = 0; i < namedNodeMap.size(); ++i) {
        QDomNode domNode = namedNodeMap.item(i);

        if (domNode.nodeType() == QDomNode::AttributeNode) {
            QDomAttr domElement = domNode.toAttr();

            if (domElement.name() == QLatin1String("DefaultTargets"))
                m_defaultTargets = domElement.value().split(QLatin1Char(';'));
            else if (domElement.name() == QLatin1String("InitialTargets"))
                m_initialTargets = domElement.value().split(QLatin1Char(';'));
            else if (domElement.name() == QLatin1String("ToolsVersion"))
                m_toolsVersion = domElement.value();
            else if (domElement.name() == QLatin1String("xmlns"))
                m_xmlns = domElement.value();
        }
    }
}
Example #16
0
void Item::processAttributes(const QDomElement &nodeElement)
{
    // process attributes
    QDomNamedNodeMap namedNodeMap = nodeElement.attributes();

    for (int i = 0; i < namedNodeMap.size(); ++i) {
        QDomNode domNode = namedNodeMap.item(i);

        if (domNode.nodeType() == QDomNode::AttributeNode) {
            QDomAttr domElement = domNode.toAttr();

            if (domElement.name() == QLatin1String("Condition"))
                m_condition = domElement.value();
            else if (domElement.name() == QLatin1String("Include"))
                m_include = domElement.value();
            else if (domElement.name() == QLatin1String("Exclude"))
                m_exclude = domElement.value();
            else if (domElement.name() == QLatin1String("Remove"))
                m_remove = domElement.value();
        }
    }

    m_name = nodeElement.nodeName();
}
QVector<Bit> AVRStudioXMLParser::GetBits(QDomNode node)
{
    QVector<Bit> bits(0);

    while(!node.isNull())
    {
        QDomNamedNodeMap attributes = node.attributes();
        Bit bit;

        for(int i = 0; i < attributes.size(); i++)
        {
            QDomNode attribute = attributes.item(i);
            if(bit.GetMappingMap()[attribute.nodeName()])
                *bit.GetMappingMap()[attribute.nodeName()] = attribute.nodeValue();
        }

        bit.SetValues(GetValues(node.childNodes()));
        bits.append(bit);

        node = node.nextSibling();
    }

    return bits;
}
Example #18
0
//Encargado de generar un nuevo archivo de registros a partir de un archivo XML
void MainWindow::on_importXML_triggered()
{
    //Se obtiene la direccion del archivo xml
    QString file = QFileDialog::getOpenFileName(this,"Importar archivo XML","","XML (*.xml)");

    //verifica que la direccion este bien
    if(!file.isEmpty()){

        //si esta abierto un archivo de registros entonces lo cierra y muestra al usuario
        //a que escoga el lugar de destino del nuevo archivo que se escribe

        //verifica que los archivos este cerrados
        if(this->fileRecord.isOpen()){
            this->fileRecord.close();
        }
        if(this->indicesFile.isOpen()){
            this->indicesFile.close();
        }

        //Limpia el vector de campos del archivo
        while(this->fileRecord.fieldsSize() != 0){
            this->fileRecord.removeField(0);
        }

        //toma la direccion del nuevo archivo de registros
        QString directory = QFileDialog::getExistingDirectory(this,"New File","");
        if(!directory.isEmpty()){
            bool val;
            //Pregunta el nombre del archivo destino
            QString fileName = QInputDialog::getText(this,"Nombre del Archivo","Escriba el nombre del archivo que desea crear",QLineEdit::Normal,"",&val);
            if(val && !fileName.isEmpty()){
                QString Path = directory + "/" + fileName + ".jjdb";
                //escribe algo, luego lo cierra y vuelve a abrir
                if(!this->fileRecord.open(Path.toStdString())){
                    this->fileRecord.open(Path.toStdString(),ios_base::out);
                    this->fileRecord.write("$$",2);
                    this->fileRecord.flush();
                    this->fileRecord.close();

                    QString indicesPath = directory + "/" + fileName + "-indices.jjdb";
                    this->indicesFile.open(indicesPath.toStdString().c_str(),ios_base::out);
                    this->indicesFile.write("$$",2);
                    this->indicesFile.flush();
                    this->indicesFile.close();

                    this->indicesFile.open(indicesPath.toStdString().c_str(),ios_base::in | ios_base::out);

                    if(this->fileRecord.open(Path.toStdString(),ios_base::in | ios_base::out)){

                        //se hace del uso de un QDomDocument que permite la lectura del xml
                        QDomDocument document;

                        //uso de un qfile
                        QFile qfile(file);

                        //verifica que archivo este abierto solamente en modo de lectura
                        if(!qfile.open(QIODevice::ReadOnly)){
                            QMessageBox::critical(this,"Error","Hubo un error en la lectura del archivo XML");
                            return;
                        }

                        //le asigna el contenido del archivo al documento que permite la lectura
                        if(!document.setContent(&qfile)){
                            QMessageBox::critical(this,"Error","Hubo un error de lectura del archivo XML");
                            return;
                        }

                        //Esta lectura se basa especificamente en tomar los elementos y crear registros
                        //a partir de ellos
                        QDomElement db = document.documentElement();

                        QDomNode fr = db.firstChild().firstChild();

                        QDomElement elem = fr.toElement();

                        //verifica que los elementos no sean nulos
                        while(!elem.isNull()){
                                QString name = elem.tagName();

                                if(!elem.hasAttributes()){
                                    QMessageBox::critical(this,"Error","El archivo XML contiene una mala estructura");
                                    return;
                                }

                                QDomNamedNodeMap map = elem.attributes();

                                char type;
                                int length;
                                int decimalPlaces = 0;
                                int key = 0;

                                if(map.size() < 3){
                                    QMessageBox::critical(this,"Error","El archivo XML contiene una mala estructura");
                                    return;
                                }

                                //toma de los elementos xml y los convierte a las caracteristicas de un registro
                                for(int i = 0; i < map.size(); i++){
                                    if(!map.item(i).isNull()){
                                        QDomNode node = map.item(i);
                                        QDomAttr attr = node.toAttr();

                                        if(attr.name() == "key"){
                                            if(attr.value() == "true"){
                                                key = 1;
                                            }
                                        }else if(attr.name() == "type"){
                                            if(attr.value() == "integer"){
                                                type = 'E';
                                            }else if(attr.value() == "real"){
                                                type = 'R';
                                            }else{
                                                type = 'C';
                                            }
                                        }else if(attr.name() == "length"){
                                            length = attr.value().toInt();
                                        }else if(attr.name() == "decimalPlaces"){
                                            decimalPlaces = attr.value().toInt();
                                        }else{
                                            QMessageBox::critical(this,"Error","El archivo XML tiene una mala estructura");
                                            return;
                                        }
                                    }else{
                                        QMessageBox::critical(this,"Error","Mala estructura del archivo XML");
                                        return;
                                    }
                                }

                                //creacion de un nuevo registro
                                Field* newField = new Field(name.toStdString(),type,key,length,decimalPlaces);
                                this->fileRecord.addField(newField);
                                elem = elem.nextSibling().toElement();
                        }

                        //cambia el tamanio de los registros del archivo
                        int rl = 0;
                        vector<Field*> fields = this->fileRecord.getFields();
                        for(int i = 0; i < fields.size(); i++){
                            rl += fields.at(i)->getLength();
                        }
                        this->fileRecord.setRecordLength(rl);

                        //limpia el mapa de indices primarios
                        this->fileRecord.cleanMap();

                        //se encarga de hacer el header del archivo y guardar los campos
                        string header = this->fileRecord.toStringHeader();
                        this->fileRecord.write(header.c_str(),header.size());
                        this->fileRecord.flush();

                        QDomElement start_data = db.firstChild().toElement();

                        //se encarga especificamente de tomar los datos del xml
                        //y los convierte en los registros
                        while(!start_data.isNull()){
                            vector<string> record;

                            QDomElement e = start_data.firstChild().toElement();
                            while(!e.isNull()){
                                record.push_back(e.text().trimmed().toStdString());
                                e = e.nextSibling().toElement();
                            }

                            //creacion de un nuevo registro
                            Record* r  = new Record(this->fileRecord.getFields(),record);
                            this->fileRecord.addRecord(r);


                            start_data = start_data.nextSibling().toElement();
                        }

                        //ahora se encarga de hacer los indices y de guardarlos en el archivo de indices
                        vector<PrimaryIndex*> indexes = this->fileRecord.getIndexes();

                        stringstream ss;
                        for(int i = 0; i < indexes.size(); i++){
                            ss<<indexes.at(i)->toString();
                            if(i != indexes.size() -1){
                                ss<<'/';
                            }
                        }
                        this->indicesFile.seekp(0,ios_base::beg);
                        this->indicesFile.write(ss.str().c_str(),ss.str().length());
                        this->indicesFile.flush();

                        //solamente cierra el archivo xml
                        qfile.close();

                        QMessageBox::information(this,"Satisfactorio","Se ha creado el archivo de registros correctamente");

                    }else{
                        QMessageBox::critical(this,"Error","Hubo un error inesperado al momento de abrir el archivo creado");
                    }
                }else{
                    QMessageBox::critical(this,"Error","Hubo un error al momento de abrir el archivo para su inicializacion");
                }
            }
        }

    }
}
bool DrugDrugInteraction::updateDomElement(QDomElement *element, QDomDocument *doc) const
{
    if (element->tagName()!="DDI")
        return false;
    element->setAttribute("i1", m_Data.value(FirstInteractorName).toString());
    element->setAttribute("i2", m_Data.value(SecondInteractorName).toString());
    element->setAttribute("i1ra", m_Data.value(FirstInteractorRouteOfAdministrationIds).toStringList().join(";"));
    element->setAttribute("i2ra", m_Data.value(SecondInteractorRouteOfAdministrationIds).toStringList().join(";"));
    element->setAttribute("l", m_Data.value(LevelCode).toString());
    element->setAttribute("a", m_Data.value(DateCreation).toString());
    element->setAttribute("lu", m_Data.value(DateLastUpdate).toString());
    element->setAttribute("v", m_Data.value(IsValid).toInt());
    element->setAttribute("rv", m_Data.value(IsReviewed).toInt());
    element->setAttribute("p", m_Data.value(PMIDsStringList).toStringList().join(";"));

    // Update risk
    QDomElement riskNode = element->firstChildElement("R");
    if (riskNode.isNull()) {
        // create risk
        QDomElement rFr = doc->createElement("R");
        rFr.setAttribute("l", "fr");
        rFr.setAttribute("t", risk("fr"));
        element->appendChild(rFr);
        QDomElement rEn = doc->createElement("R");
        rEn.setAttribute("l", "en");
        rEn.setAttribute("t", risk("en"));
        element->appendChild(rEn);
    } else {
        if (riskNode.attribute("l").compare("fr",Qt::CaseInsensitive)==0) {
            riskNode.setAttribute("t", risk("fr"));
            QDomElement rEn = riskNode.nextSiblingElement("R");
            if (rEn.isNull()) {
                rEn = doc->createElement("R");
                rEn.setAttribute("l", "en");
                element->appendChild(rEn);
            }
            rEn.setAttribute("t", risk("en"));
        } else if (riskNode.attribute("l").compare("en",Qt::CaseInsensitive)==0) {
            riskNode.setAttribute("t", risk("en"));
            QDomElement rFr = riskNode.nextSiblingElement("R");
            if (rFr.isNull()) {
                rFr = doc->createElement("R");
                rFr.setAttribute("l", "fr");
                element->appendChild(rFr);
            }
            rFr.setAttribute("t", risk("fr"));
        }
    }

    // Update management
    QDomElement manNode = element->firstChildElement("M");
    if (manNode.isNull()) {
        // create management
        QDomElement rFr = doc->createElement("M");
        rFr.setAttribute("l", "fr");
        rFr.setAttribute("t", management("fr"));
        element->appendChild(rFr);
        QDomElement rEn = doc->createElement("M");
        rEn.setAttribute("l", "en");
        rEn.setAttribute("t", management("en"));
        element->appendChild(rEn);
    } else {
        if (manNode.attribute("l").compare("fr",Qt::CaseInsensitive)==0) {
            manNode.setAttribute("t", management("fr"));
            QDomElement rEn = manNode.nextSiblingElement("M");
            if (rEn.isNull()) {
                rEn = doc->createElement("R");
                rEn.setAttribute("l", "en");
                element->appendChild(rEn);
            }
            rEn.setAttribute("t", management("en"));
        } else if (manNode.attribute("l").compare("en",Qt::CaseInsensitive)==0) {
            manNode.setAttribute("t", risk("en"));
            QDomElement rFr = manNode.nextSiblingElement("M");
            if (rFr.isNull()) {
                rFr = doc->createElement("R");
                rFr.setAttribute("l", "fr");
                element->appendChild(rFr);
            }
            rFr.setAttribute("t", management("fr"));
        }
    }

    // Update doses
//    QDomElement dose = element.firstChildElement("D");
//    while (!dose.isNull()) {
//        DrugDrugInteractionDose *ddidose = 0;
//        if (dose.attribute("i") == "1") {
//            ddidose = &m_FirstDose;
//        } else {
//            ddidose = &m_SecondDose;
//        }
//        if (dose.attribute("uf").toInt()==1) {
//            ddidose->setData(DrugDrugInteractionDose::UsesFrom, true);
//            ddidose->setData(DrugDrugInteractionDose::FromValue , dose.attribute("fv"));
//            ddidose->setData(DrugDrugInteractionDose::FromUnits, dose.attribute("fu"));
//            ddidose->setData(DrugDrugInteractionDose::FromRepartition , dose.attribute("fr"));
//        } else if (dose.attribute("ut").toInt()==1) {
//            ddidose->setData(DrugDrugInteractionDose::UsesTo, true);
//            ddidose->setData(DrugDrugInteractionDose::ToValue , dose.attribute("tv"));
//            ddidose->setData(DrugDrugInteractionDose::ToUnits, dose.attribute("tu"));
//            ddidose->setData(DrugDrugInteractionDose::ToRepartition , dose.attribute("tr"));
//        }
//        dose = dose.nextSiblingElement("D");
//    }

    // Update formalized risk
    QDomElement formNode = element->firstChildElement("F");
    if (!formNode.isNull()) {
        QDomNamedNodeMap attributeMap = formNode.attributes();
        for(int i=0; i < attributeMap.size(); ++i) {
            formNode.removeAttribute(attributeMap.item(i).nodeName());
        }
    }
    if (m_Formalized.count() > 0) {
        QHashIterator<QString,QString> i(m_Formalized);
        while (i.hasNext()) {
            i.next();
            formNode.setAttribute(i.key(), i.value());
        }
    }
    return true;
}
Example #20
0
void FlickrCollector::parseDomTreeSub(int level, QDomElement parentElement)
{
  QDomNode node;
  // a bit inefficient declaring these here
  bool farmFlag = false;
  bool secretFlag = false;
  bool idFlag = false;
  bool serverFlag = false;
  QString serverStr;
  QString farmStr;
  QString idStr;
  QString secretStr;
  QString urlStr;

  node = parentElement.firstChild();

  while ( !node.isNull() )
    {
      if (node.nodeName() == "photo")
    {
      QDomNamedNodeMap attributes = node.attributes();
      for(int i = 0; i<attributes.size(); ++i)
        {
          QDomAttr attribute = attributes.item(i).toAttr();
          if (attribute.name() == "farm" && !farmFlag)
        {
          farmStr = attribute.value();
          farmFlag = true;
        }
          else if (attribute.name() == "server" && !serverFlag)
        {
          serverStr = attribute.value();
          serverFlag = true;
        }
          else if (attribute.name() == "id" && !idFlag)
        {
          idStr = attribute.value();
          idFlag = true;
        }
          else if (attribute.name() == "secret" && !secretFlag)
        {
          secretStr = attribute.value();
          secretFlag = true;
        }
        } /* for */
      urlStr.clear();
      urlStr.append("http://farm").append(farmStr)
        .append(".staticflickr.com/");
      urlStr.append(serverStr).append("/");
      urlStr.append(idStr).append("_").append(secretStr)
        .append("_z.jpg");

      itemList.append(urlStr);

      idFlag = secretFlag = farmFlag = serverFlag = false;
      idStr.clear();
      farmStr.clear();
      serverStr.clear();
      secretStr.clear();
    }
      QDomElement body = node.toElement();
      parseDomTreeSub(level+1, body);
      node = node.nextSibling();
    }
}
Example #21
0
void mafViewCompoundConfigurator::parseDocument(QDomNode current, QObject *parent) {
    QDomNodeList dnl = current.childNodes();
    for (int n=0; n < dnl.count(); ++n) {
        QDomNode node = dnl.item(n);
        if (node.nodeType() == QDomNode::ElementNode) {
            QDomElement ce = node.toElement();
            QDomNamedNodeMap attributes = ce.attributes();
            QString elem_name = ce.tagName();
            if (elem_name == "splitter") {
                mafSplitter *splitter = new mafSplitter(Qt::Horizontal, (QWidget *)parent);
                if (parent == NULL) {
                    // parent is the root object, this is the first splitter created
                    m_RootObject = splitter;
                }
                QString sepThikness = attributes.namedItem("separatorThikness").nodeValue();
                QString sepEnabled = attributes.namedItem("enableSeparator").nodeValue();
                splitter->setHandleWidth(sepThikness.toInt());
                QString orientation = attributes.namedItem("orientation").nodeValue();
                if (orientation == "vertical") {
                    // Check only for vertical, horizontal is the default.
                    splitter->setOrientation(Qt::Vertical);
                }
                QStringList sizesString = attributes.namedItem("sizes").nodeValue().split(",", QString::SkipEmptyParts);
                QList<int> sizes;
                for (int s = 0; s < sizesString.count(); ++s) {
                    sizes.append(sizesString[s].toInt());
                }
                splitter->setSizes(sizes);
                // Check if there are children and parse them...
                QDomNodeList splitter_dnl = node.childNodes();
                if (splitter_dnl.count() > 0) {
                    parseDocument(node, splitter);
                }
                QSplitterHandle *handler = splitter->handle(1);
                handler->setEnabled(sepEnabled.toInt() != 0);
            } else if (elem_name == "view") {
                // view objects are added at the parent splitter.
                QString viewClassType = attributes.namedItem("classtype").nodeValue();
                // Instantiate the class type
                mafCore::mafObjectBase *obj = mafNEWFromString(viewClassType);
                // Then extract all the attributes representing the object's properties.
                int s = attributes.size();
                int i = 0;
                for (; i < s; ++i) {
                    QDomNode n(attributes.item(i));
                    if (n.nodeName() != "classtype") {
                        QByteArray ba(n.nodeName().toAscii());
                        bool isOk(obj->setProperty(ba.constData(), n.nodeValue()));
                        if (!isOk) {
                            qWarning() << mafTr("Problem assigning property named: %1 to view of type: %2").arg(n.nodeName(), viewClassType);
                        }
                    }
                }
                mafSplitter *parentSplitter = qobject_cast<mafSplitter *>(parent);
                if (parentSplitter) {
                    // and add it to the splitter.
                    parentSplitter->addView(obj);
                }
                // Check if there are children and parse them...
                QDomNodeList view_dnl = node.childNodes();
                if (view_dnl.count() > 0) {
                    parseDocument(node, obj);
                }
                // The splitter retain the view object, so we can release the instance.
                mafDEL(obj);
            } else if (elem_name == "visualpipe") {
                // Visual pipe to plug into the previous created view...
                QVariant visualPipeClassType(attributes.namedItem("classtype").nodeValue());
                QString dataType(attributes.namedItem("datatype").nodeValue());
                QVariantHash h;
                h.insert(dataType, visualPipeClassType);
                mafCore::mafObjectBase *viewObj = dynamic_cast<mafCore::mafObjectBase *>(parent);
                if (viewObj) {
                    viewObj->setProperty("visualPipeHash", h);

                    int s = attributes.size();
                    int i = 0;
                    QVariantHash propertyHash;
                    for (; i < s; ++i) {
                        QDomNode n(attributes.item(i));
                        if (n.nodeName() != "classtype" && n.nodeName() != "datatype") {
                            propertyHash.insert(n.nodeName(), n.nodeValue());
                        }
                    }
                    if (propertyHash.size() > 0) {
                        // Found some custom properties used to initialize the pipe
                        QString vp(visualPipeClassType.toString());
                        bool isOk(viewObj->metaObject()->invokeMethod(viewObj, "plugPipeParametersHashItem",
                                                    Q_ARG(QString, vp),
                                                    Q_ARG(QVariantHash, propertyHash)));
                        if (!isOk) {
                            qWarning() << mafTr("Problem invoking method used to plug the pipe's parameter for pipe: %1").arg(visualPipeClassType.toString());
                        }
                    }
                }
            } else {
                qWarning() << mafTr("Unrecognized element named: ") << elem_name;
            }
        }
    }
}
/**
* \brief This function verify if a similar element is not already written and write the element at the good place
* \author Jules Gorny - ALCoV team, ISIT, UMR 6284 UdA – CNRS
* \param doc : QDomDocument containing the xml tree
* \param elemName : Name of the XML element
* \param elemValue : Value of the XML element
* \param attributes : QMap<QString, QString> with the attribute's name in key and the atttribute's value in value
* \param parentsStr : A string containing a hierarchy of parents written like .../.../grandFather/father (used to compare the parents of existing elements and the new one)
* \param parentsAttr : QMap<QString, QMap<QString, QString>> containing the parent name in the key and a map build like the attributes param in the value (used to compare the parents of existing elements and the new one)
* \param ui : in case we want to write a message to the user.
**/
void writeElement(QDomDocument &doc, QDomElement &addedNode, QString elemName, QString elemValue, QMap<QString, QString> attributes, QString parentsStr, QMap<QString, QMap<QString, QString>> parentsAttr, Ui::MainWindow *ui)
{
	QStringList parents;
	if(parentsStr != "")
		parents = parentsStr.split("/");

	/**
	* We try to find where we want to include our new node. For that we browse the XML tree keeping a track on the closer parent of our node we found.
	* This closer parent is named "last parent" cause it's the last we found while going deeper in the tree.
	**/
	QDomNodeList lastParentFoundList;
	QDomNode ourActualLastParent;
	//If we have at least one parent, we search the first one (it will be "Patient")
	if( parents.size() > 0 )
	{
		lastParentFoundList = doc.elementsByTagName(parents.at(0));
		ourActualLastParent = lastParentFoundList.at(0);
	}
	//If we don't have parents
	else
	{
		//And if there is no Patient node 
		if( doc.elementsByTagName("Patient").size() == 0 )
		{
			//We create the element at the root (if the program is well written, it's supposed to be a new Patient node)
			addedNode = doc.createElement(elemName);
			if( elemValue != "" )
			{
				QDomText nameText = doc.createTextNode(elemValue);
				addedNode.appendChild(nameText);
			}
			if( attributes.size() > 0 )
			{
				QMap<QString, QString>::Iterator it;
				for( it = attributes.begin() ; it != attributes.end() ; ++it)
					addedNode.setAttribute(it.key(), it.value());
			}
			doc.appendChild(addedNode);
		}
	}

	//The lastParent is now initialized with "Patient", we can browse the rest of the parents tree.
	for( int p=1; p<parents.size(); p++ )
	{
		//We search the list of nodes corresponding to second older parent name (after Patient)
		lastParentFoundList = ourActualLastParent.toElement().elementsByTagName(parents.at(p));
		//If we can't find any parent candidate, there is a problem in the program ...
		if( lastParentFoundList.size() == 0 )
		{
			addProgressMessage(ui, "Looks like the developper didn't do a great job. The parents list doesn't match the XML file we are browsing.", Qt::black, "", false);
		}
		//If there is at least one parent node found with that name, we will compare the attribute
		else
		{
			bool weFoundWhatWeWanted = false;
			//Browse the different parent candidates
			for( int f=0; f<lastParentFoundList.size(); f++ )
			{
				//We estimate that the attributes correspond to what we want
				bool areAllAttributesSimilar = true;
				QDomNamedNodeMap parentsAttributes = lastParentFoundList.at(f).attributes();
				//We browse the attribute to find if one attribute doesn't correspond
				for(int a=0; a<parentsAttributes.size(); a++)
				{
					QString parentAttrName = parentsAttributes.item(a).toAttr().name();
					QString parentAttrValue = parentsAttributes.item(a).toAttr().value();
					QMap<QString, QString> tempAttr = parentsAttr.find(parents.at(p)).value();
					//In that case, we continue to browse the different parent candidates
					if( !tempAttr.contains(parentAttrName) || tempAttr.find(parentAttrName).value() != parentAttrValue)
					{
						areAllAttributesSimilar = false;
						break;
					}
				}
				//If we found the perfect candidate, we keep it and stop brownsing the candidates. We can go deeper in the tree.
				if( areAllAttributesSimilar )
				{
					ourActualLastParent = lastParentFoundList.at(f);
					weFoundWhatWeWanted = true;
					break;
				}
			}
			//If we didn't find any corresponding parent, there is a problem in the program ...
			if( !weFoundWhatWeWanted )
			{
				addProgressMessage(ui, "Looks like the developper didn't do a great job. The parents list doesn't match the XML file we are browsing.", Qt::black, "", false);
			}
		}
	}
	
	//We finally found our closer parent !
	QDomNodeList sameElementFoundList;
	sameElementFoundList = ourActualLastParent.toElement().elementsByTagName(elemName);
	bool isAnElementSimilar = false;
	//We try to find a similar element (Name + attributes)
	for( int f=0; f<sameElementFoundList.size(); f++ )
	{
		bool areAllAttributesSimilar = true;
		QDomNamedNodeMap parentsAttributes = sameElementFoundList.at(f).attributes();
		for(int a=0; a<parentsAttributes.size(); a++)
		{
			QString parentAttrName = parentsAttributes.item(a).toAttr().name();
			QString parentAttrValue = parentsAttributes.item(a).toAttr().value();
			if( !attributes.contains(parentAttrName) || attributes.find(parentAttrName).value() != parentAttrValue)
			{
				areAllAttributesSimilar = false;
				break;
			}
		}
		if( areAllAttributesSimilar )
		{
			isAnElementSimilar = true;
			addedNode = sameElementFoundList.at(f).toElement();
			break;
		}
	}

	//If the element definitly doesn't exists, we create it
	if( !isAnElementSimilar )
	{
		addedNode = doc.createElement(elemName);
		if( elemValue != "" )
		{
			QDomText nameText = doc.createTextNode(elemValue);
			addedNode.appendChild(nameText);
		}
		if( attributes.size() > 0 )
		{
			QMap<QString, QString>::Iterator it;
			for( it = attributes.begin() ; it != attributes.end() ; ++it)
				addedNode.setAttribute(it.key(), it.value());
		}
		ourActualLastParent.toElement().appendChild(addedNode);
	}
}
void DialogEditNodeTable::ApplyButtonPressed()
{
    XmlEditCommandAggregator* commandAggregator = new XmlEditCommandAggregator(m_pXmlDocument);

    //Get all the attributes
    QDomNamedNodeMap attributes = m_node.attributes();

    //First remove the attributes the isn't present now
    for(int i=attributes.size()-1; i >= 0; i--)
    {
        bool attributePresent = false;
        QString attributeName = attributes.item(i).nodeName();

        //For each present attribute in the table
        for(int k=0; k < m_pTable->rowCount() && !attributePresent; ++k)
        {
            QString tableAttributeName = m_pTable->item(k, 0)->text();

            if(tableAttributeName != "" && attributeName == tableAttributeName)
            {
                attributePresent = true;
            }
        }

        //If the attribute is no longer present
        if(!attributePresent)
        {
            //Remove from the list
            attributes.removeNamedItem(attributeName);
            //Add an action to remove it
            commandAggregator->AddCommand(new XmlEditCommandRemoveAttribute(m_pXmlDocument, m_identifierNumber, attributeName));
        }
    }

    //Now the attributesList contains all the attribute that is present in the node
    //In the table it can be present more attribute (newly added ones)

    //Add the attributes that isn't present yet (new attribute) and modify the attributes already present
    for(int k=0; k < m_pTable->rowCount(); ++k)
    {
        bool attributeAlreadyPresent = false;
        QString tableAttributeName = m_pTable->item(k, 0)->text();
        QString tableAttributeValue = m_pTable->item(k, 1)->text();

        QString previousAttributeValue;

        //Not add the empty attribute name
        if(tableAttributeName != "")
        {
            //For each attribute already present
            for(int i=0;i < attributes.size() && !attributeAlreadyPresent; ++i)
            {
                if(attributes.item(i).nodeName() == tableAttributeName)
                {
                    attributeAlreadyPresent = true;
                    previousAttributeValue = attributes.item(i).nodeValue();
                }
            }

            //If the attribute is not present yet
            if(!attributeAlreadyPresent)
            {
                //Add an action to add it
                commandAggregator->AddCommand(new XmlEditCommandAddAttribute(m_pXmlDocument, m_identifierNumber, tableAttributeName,
                                                                             tableAttributeValue));
            }
            else //The attribute is yet present so maybe its value is changed
            {
                //If the value of the already present attribute is changed
                if(previousAttributeValue != tableAttributeValue)
                {
                    //Add an action to change its value
                    commandAggregator->AddCommand(new XmlEditCommandEditAttribute(m_pXmlDocument, m_identifierNumber, tableAttributeName,
                                                                                 tableAttributeValue));
                }
            }
        }
    }

    const QString& currentValue = m_pValueLine->text();

    //If the value is changed set the new
    if(m_node.toElement().text() != currentValue)
    {
        commandAggregator->AddCommand(new XmlEditCommandSetNodeValue(m_pXmlDocument, m_identifierNumber, currentValue));
    }

    if(commandAggregator->Size() > 0)
    {
        m_pXmlEditCommandInvoker->ExecuteACommand( commandAggregator );
    }
    QDialog::accept();
}
Example #24
0
void UPnpDeviceDesc::_InternalLoad( QDomNode oNode, UPnpDevice *pCurDevice )
{
    QString pin = GetMythDB()->GetSetting( "SecurityPin", "");
    pCurDevice->m_securityPin = !(pin.isEmpty() || pin == "0000");

    for ( oNode = oNode.firstChild();
          !oNode.isNull();
          oNode = oNode.nextSibling() )
    {
        QDomElement e = oNode.toElement();

        if (e.isNull())
            continue;

        // TODO: make this table driven (using offset within structure)
        if ( e.tagName() == "deviceType" )
            SetStrValue( e, pCurDevice->m_sDeviceType);
        else if ( e.tagName() == "friendlyName" )
            SetStrValue( e, pCurDevice->m_sFriendlyName );
        else if ( e.tagName() == "manufacturer" )
            SetStrValue( e, pCurDevice->m_sManufacturer );
        else if ( e.tagName() == "manufacturerURL" )
            SetStrValue( e, pCurDevice->m_sManufacturerURL );
        else if ( e.tagName() == "modelDescription" )
            SetStrValue( e, pCurDevice->m_sModelDescription);
        else if ( e.tagName() == "modelName" )
            SetStrValue( e, pCurDevice->m_sModelName );
        else if ( e.tagName() == "modelNumber" )
            SetStrValue( e, pCurDevice->m_sModelNumber );
        else if ( e.tagName() == "modelURL" )
            SetStrValue( e, pCurDevice->m_sModelURL );
        else if ( e.tagName() == "serialNumber" )
            SetStrValue( e, pCurDevice->m_sSerialNumber );
        else if ( e.tagName() == "UPC" )
            SetStrValue( e, pCurDevice->m_sUPC );
        else if ( e.tagName() == "presentationURL" )
            SetStrValue( e, pCurDevice->m_sPresentationURL );
        else if ( e.tagName() == "UDN" )
            SetStrValue( e, pCurDevice->m_sUDN );
        else if ( e.tagName() == "iconList" )
            ProcessIconList( oNode, pCurDevice );
        else if ( e.tagName() == "serviceList" )
            ProcessServiceList( oNode, pCurDevice );
        else if ( e.tagName() == "deviceList" )
            ProcessDeviceList ( oNode, pCurDevice );
        else if ( e.tagName() == "mythtv:X_secure" )
            SetBoolValue( e, pCurDevice->m_securityPin );
        else if ( e.tagName() == "mythtv:X_protocol" )
            SetStrValue( e, pCurDevice->m_protocolVersion );
        else
        {
            // Not one of the expected element names... add to extra list.
            QString sValue = "";
            SetStrValue( e, sValue );
            NameValue node = NameValue(e.tagName(), sValue);
            QDomNamedNodeMap attributes =  e.attributes();
            for (int i = 0; i < attributes.size(); i++)
            {
                node.AddAttribute(attributes.item(i).nodeName(),
                                  attributes.item(i).nodeValue(),
                                  true); // TODO Check whether all attributes are in fact requires for the device xml
            }
            pCurDevice->m_lstExtra.push_back(node);
        }
    }
}