Seite 1 von 1

XML datei lesen

Verfasst: 8. März 2009 19:51
von anno1988
Hallo,

ich habe mal eine grundlegende frage zu xml. Ich habe mir da mal eine xml datei erstellt und möchte diese einlesen. Jetzt musste ich aber feststellen, dass im rootzweig ich keine tag platzieren kann. Ohne diese creation_time geht es einwandfrei das einlesen.

Wie bekomme ich denn diese info trotzdem in meinem xml file unter, ohne sie im rootzweig platzieren zu müssen.

Code: Alles auswählen


<?xml version="1.0" encoding="UTF-8">
<dir creation_dt="2009-01-10 20:20:20">
	<file>
		file1.txt
	</file>
	<file>
		file2.txt
	</file>
</dir>



Verfasst: 8. März 2009 21:41
von franzf
Also, ich hab damit keinerlei Probleme.
Zeig doch mal, wie du das XML einliest!

Verfasst: 8. März 2009 23:05
von anno1988

Code: Alles auswählen


QDomDocument doc("mydocument");
 QFile file("mydocument.xml");
 if (!file.open(QIODevice::ReadOnly))
     return;
 if (!doc.setContent(&file)) {
     file.close();
     return;
 }
 file.close();

 // print out the element names of all elements that are direct children
 // of the outermost element.
 QDomElement docElem = doc.documentElement();

 QDomNode n = docElem.firstChild();
 while(!n.isNull()) {
     QDomElement e = n.toElement(); // try to convert the node to an element.
     if(!e.isNull()) {
         cout << qPrintable(e.tagName()) << endl; // the node really is an element.
     }
     n = n.nextSibling();
 }

Verfasst: 8. März 2009 23:50
von franzf
QDomDocument::setContent() nimmt auch noch weitere Parameter auf, um dann die exakte Fehlerquelle herauszufinden. Das kannst du z.B. beim Fehlschlag des setContent() ausgeben.

Ich hab das hier versucht, und es geht:

Code: Alles auswählen

#include <QtXml>
#include <QtDebug>

const QString XML_DATA = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \
<!DOCTYPE xml> \
<doc creation_dt=\"2009-01-10 20:20:20\"> \
<nnnnn>Hello</nnnnn> \
<oooo>Blubb</oooo> \
</doc>";

int main()
{
    QDomDocument doc;
    doc.setContent( XML_DATA );
    QDomElement root = doc.documentElement();
    qDebug() << root.tagName();

    QDomAttr testAttr = root.attributeNode("creation_dt");
    qDebug() << testAttr.value();

    qDebug() << doc.toString();

    return 0;
}
QIODevice hat dann auch noch die Methode "errorString()", mit der du vllt. beim Fehlschlag beim Öffnen was erfahren kannst.

Verfasst: 9. März 2009 08:27
von anno1988
ok danke werde ich mal ausprobieren.