XML QDomDocument saubere headers

Code-Schnippsel, oder Tipps und Tricks, die einem beim Programmieren mit Qt helfen können.
Antworten
patrik08
Beiträge: 746
Registriert: 27. Februar 2006 10:48
Wohnort: DE Freiburg

XML QDomDocument saubere headers

Beitrag von patrik08 »

Es ist sehr einfach ein xml in einem text stream oder sonst in einem file zu speichern ....

Aber auf die QDomDocument methode einen sauberen header

<?xml version="1.0"?>


hinzubringen ist nicht jedermansache.... bei bir hat es 2 monaten gedauert bis ich entlichl das wie? gefunden habe....

Die vorteilen mann muss sich nicht besonders fuer die codierung besorgen mit umlaut unsw...

Und es gibt noch eine interessante methode....
QDomDocumentFragment einen ganzen child in eine node zu setzen oder ein andere xml file.... wann ich dass auch entecke verrate ich es gerne...

Oder kennt jemand bereits die methode ... wie?

Code: Alles auswählen

#include <QtDebug>

int main()
{
   QDomDocument doc;
   QDomProcessingInstruction header = doc.createProcessingInstruction( "xml", "version=\"1.0\"" );
   doc.appendChild( header );
   QDomElement root = doc.createElement( "test" );
   doc.appendChild( root );

   qDebug() << doc.toString();
   return 0;
}


/* resultat ....*/
/*
 $ ./xml
"<?xml version="1.0"?>
<test/>
"
*/
patrik08
Beiträge: 746
Registriert: 27. Februar 2006 10:48
Wohnort: DE Freiburg

Beitrag von patrik08 »

Also gewisse experte behaupten dass QDomDocumentFragment ein bug hat und nicht geht......

Da es wichtig ist xml dokumente zu lesen und gewisse noden zwichen zu speichern ohne neu zu schreiben oder meherere xml file zu einen buendeln um es mit xslt zu convertieren habe ich einfach die QDomDocument class erweitert um die wichtige funktionen zu haben die ich auch im php5 habe und kenne......

somit sind die xml dokumente mit wenig zeilen geschrieben.....
beisbiel....

Code: Alles auswählen

   QString filexmleternal = "./qtpage.xml";
   Qxml doc = Qxml("utf-8");
   doc.SetstreamFile("./devresult.xml");
   QDomElement root = doc.createElement( "root" );
   doc.appendChild( root );
   QDomElement big = doc.createElement( "big" );
   /* insert fragment as file */
   big.appendChild(doc.insertFragmentorFile(filexmleternal));  /* insert the external file -or a tag fragment */
   root.appendChild( big );
   QDomElement next = doc.createElement( "to_next" );
   /* insert fragment as tag */
   next.appendChild(doc.insertFragmentorFile("<hello>by</hello>"));  /* insert the external file -or a tag fragment */
   root.appendChild( next );
   doc.Print();
   doc.saveXML();

dass resultat ein sauberes xml dom document....

Code: Alles auswählen

<?xml version="1.0" encoding="utf-8"?>
<root>
  <big>....</big>
  <to_next>
  <hello>by</hello>
  </to_next>
</root>


source ...

Code: Alles auswählen

#include "qxml.h"

/* save this file as qxml.cpp */
/* constructor */
Qxml::Qxml( QString codec )
{
    if (codec.size() < 1) {
    decode ="utf-8";
    } else {
    decode =codec;   
    }
    /* Make a header  */
	header = QDomDocument::createProcessingInstruction( "xml",QString("version=\"1.0\" encoding=\"%1\"" ).arg(decode));
    appendChild( header );
}
/* save doc if is a streamfiele */
bool Qxml::saveXML()
{
   if (is_file(stream_on_file)) {
   return saveXML(stream_on_file);
   }  
return false;   
}
/* print on cosole the result */
void Qxml::Print()
{
    QTextStream out(stdout);
    out << Qxml::toString(); 
}

/* Append fragment or a real xml file */
QDomElement Qxml::insertFragmentorFile( QString fragment )
{
    bool check;
    /* if is a file insert dom tree and convert to element */
    if (is_file(fragment)) {
        QFile ext_file(fragment);
        ext_file.open( QIODevice::ReadOnly);
        QDomDocument dom_external;
        check = dom_external.setContent(&ext_file); 
           if ( check ) {
            QDomElement root_extern = dom_external.documentElement(); 
            QDomNode newnode = root_extern.firstChild();
            QDomNode treallsub = dom_external.importNode(newnode,true);
            ext_file.close(); 
            return treallsub.toElement(); 
           } else {
            ext_file.close(); 
            return ErrorDom();
           }               
    } else {
    /* is not a file */
    QTextCodec *setcurrentcodec;
    if (decode == "utf-8") {
    setcurrentcodec = QTextCodec::codecForMib(106);  /* utf8 */  
    } else {
    setcurrentcodec = QTextCodec::codecForMib(4);  /* latin iso */
    }
        if (stream_on_file.size() > 0) {
                QFile f( stream_on_file );
                if ( f.open( QFile::WriteOnly | QFile::Text ) ) {
                QTextStream sw( &f );
                sw.setCodec(setcurrentcodec);
                sw << QString("<?xml version=\"1.0\"?>\n<dummyroot>%1</dummyroot>").arg(fragment);
                f.close();
                    if (is_file(stream_on_file)) {
                    return insertFragmentorFile(stream_on_file);
                    }
                }
         } 
    return ErrorDom();
    }
}
/* return on error an error tag */
QDomElement Qxml::ErrorDom()
{
    QDomElement errorelement = QDomDocument::createElement( "error" );
    return errorelement;
}
/* setup a file to stream fragments */
void Qxml::SetstreamFile( QString sfile )
{
    stream_on_file = sfile;
}


QString Qxml::StringtoXML( QString t )
{
  //the following checks are necessary before exporting
  //strings to XML. see http://hdf.ncsa.uiuc.edu/HDF5/XML/xml_escape_chars.html for details
  QString text = t;
  text.replace("&", "&");   /*  qt4 toUtf8 dont replace && */
  text.replace("\"",""");
  text.replace("'", "&apos;");
  text.replace("<", "<");
  text.replace(">", ">");
  text.replace("\n", "
");
  text.replace("\r", "
");
  return text;
}
/* save to a specific file */
bool Qxml::saveXML(QString fullFileName)
{
    QTextCodec *setcurrentcodec;
    if (decode == "utf-8") {
    setcurrentcodec = QTextCodec::codecForMib(106);  /* utf8 */  
    } else {
    setcurrentcodec = QTextCodec::codecForMib(4);  /* latin iso */
    }
        QFile f( fullFileName );
                if ( f.open( QFile::WriteOnly | QFile::Text ) ) {
                QTextStream sw( &f );
                sw.setCodec(setcurrentcodec);
                sw << Qxml::toString();
                f.close();
                    if (is_file(fullFileName)) {
                    return true;
                    }
                }
return false;
}

/* checker if is file exist */
bool Qxml::is_file(QString fullFileName)
{
    QFile f( fullFileName );
	if ( f.exists() ) {
    return true;
	} else {
	return false;
    }
}
/* remove file */
bool Qxml::xml_unlink(QString fullFileName)
{
    QFile f( fullFileName );
	if ( is_file( fullFileName ) ) {
       if (f.remove()) {
        return true;
       }
	}
return false;
}



header ...

Code: Alles auswählen

#ifndef QXML_H
#define QXML_H
/* save this file as qxml.h dont forget to set QT += xml on your pro file */
#include <QDomDocument>
#include <QtDebug>
#include <QDebug> 
#include <QSettings>
#include <QDomDocument>
#include <QDomElement>
#include <QDomImplementation>
#include <QDomProcessingInstruction>
#include <QFile>
#include <QTextCodec>

class Qxml : public QDomDocument
{
public:
	Qxml::Qxml( QString codec ); /* utf-8 - ISO-8859-1 */
    QString decode;
    inline QString Getdecode() { return decode; }
    QDomElement insertFragmentorFile( QString fragment ); /* insert xml file or tag fragment */
    QString StringtoXML( QString t );  /* xml_escape_chars */
    void SetstreamFile( QString sfile );  /* set a work file */
    bool saveXML(QString fullFileName);  /* save to external file */
    bool saveXML();  /* save to work file if exist */
    void Print();  /* print to console */
protected:
    bool is_file(QString fullFileName);
    bool xml_unlink(QString fullFileName);
private:
    QDomProcessingInstruction header;
    QString stream_on_file; 
    QDomElement ErrorDom();  /* on error return </error> tag */
};
//
#endif // QXML_H

Antworten