Created
September 29, 2013 20:01
-
-
Save skyhisi/6756013 to your computer and use it in GitHub Desktop.
Basic XInclude processor written using Qt QXmlStreamReader/QXmlStreamWriter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QtCore> | |
int main(int argc, char** argv) | |
{ | |
QCoreApplication app(argc, argv); | |
if (argc < 2) | |
{ | |
qDebug() << "Usage:" << argv[0] << "INFILE OUTFILE"; | |
return 1; | |
} | |
QFile inFile(argv[1]); | |
if (!inFile.open(QIODevice::ReadOnly)) | |
{ | |
qDebug() << "Error opening file:" << inFile.errorString(); | |
return 1; | |
} | |
QFile outFile(argv[2]); | |
if (!outFile.open(QIODevice::WriteOnly)) | |
{ | |
qDebug() << "Error opening file:" << outFile.errorString(); | |
return 1; | |
} | |
QXmlStreamReader reader(&inFile); | |
QXmlStreamWriter writer(&outFile); | |
while (reader.readNext() != QXmlStreamReader::Invalid) | |
{ | |
if ( | |
(reader.tokenType() == QXmlStreamReader::StartElement) && | |
(reader.namespaceUri() == "http://www.w3.org/2001/XInclude") && | |
(reader.name() == "include") | |
) | |
{ | |
const QString parseType(reader.attributes().value("parse").toString()); | |
const QString href(reader.attributes().value("href").toString()); | |
if (parseType == "text") | |
{ | |
QFile incFile(href); | |
if (incFile.open(QIODevice::ReadOnly)) | |
{ | |
const QByteArray data(incFile.readAll()); | |
writer.writeCharacters(QString::fromLocal8Bit(data.data(), data.size())); | |
} | |
else | |
{ | |
qDebug() << "Error opening file:" << incFile.errorString(); | |
} | |
} | |
else if (parseType == "xml") | |
{ | |
QFile incFile(href); | |
if (incFile.open(QIODevice::ReadOnly)) | |
{ | |
QXmlStreamReader incReader(&incFile); | |
while (incReader.readNext() != QXmlStreamReader::Invalid) | |
{ | |
switch (incReader.tokenType()) | |
{ | |
case QXmlStreamReader::StartElement: | |
case QXmlStreamReader::EndElement: | |
case QXmlStreamReader::Characters: | |
case QXmlStreamReader::Comment: | |
case QXmlStreamReader::ProcessingInstruction: | |
writer.writeCurrentToken(incReader); | |
} | |
} | |
} | |
else | |
{ | |
qDebug() << "Error opening file:" << incFile.errorString(); | |
} | |
} | |
else | |
{ | |
qDebug() << "Unknown parse type" << parseType; | |
} | |
if (reader.readNext() != QXmlStreamReader::EndElement) | |
{ | |
qDebug() << "Expected EndElement after include StartElement"; | |
} | |
} | |
else | |
{ | |
writer.writeCurrentToken(reader); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment