C++/Qt/QDomDocument
Get XML element by tag name
Foundations of Qt Development\Chapter08\xmldommodify\main.cpp
/*
* Copyright (c) 2006-2007, Johan Thelin
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of APress nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <QFile>
#include <QTextStream>
#include <QDomDocument>
#include <QDomElement>
#include <QDomText>
int main( int argc, char **argv )
{
QFile inFile( "simple.xml" );
if( !inFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
qDebug( "Failed to open file for reading." );
return 0;
}
QDomDocument document;
if( !document.setContent( &inFile ) )
{
qDebug( "Failed to parse the file into a DOM tree." );
inFile.close();
return 0;
}
inFile.close();
QDomElement documentElement = document.documentElement();
QDomNodeList elements = documentElement.elementsByTagName( "bar" );
if( elements.size() == 0 )
{
QDomElement bar = document.createElement( "bar" );
documentElement.insertBefore( bar, QDomNode() );
}
else if( elements.size() == 1 )
{
QDomElement bar = elements.at(0).toElement();
QDomElement baz = document.createElement( "baz" );
baz.setAttribute( "count", QString::number( bar.elementsByTagName( "baz" ).size() + 1 ) );
bar.appendChild( baz );
}
QFile outFile( "simple-modified.xml" );
if( !outFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
{
qDebug( "Failed to open file for writing." );
return 0;
}
QTextStream stream( &outFile );
stream << document.toString();
outFile.close();
return 0;
}
Put table to text document
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef XMLWRITER_H
#define XMLWRITER_H
#include <QDomDocument>
class QTextDocument;
class XmlWriter
{
public:
XmlWriter(QTextDocument *document) : textDocument(document) {}
QDomDocument *toXml();
private:
void processBlock(QDomElement &parent, const QTextBlock &block);
void processFrame(QDomElement &parent, QTextFrame *frame);
void processTable(QDomElement &parent, QTextTable *table);
void processTableCell(QDomElement &parent, const QTextTableCell &cell);
QDomDocument *document;
QTextDocument *textDocument;
};
#endif
#include <QtGui>
#include "xmlwriter.h"
QDomDocument *XmlWriter::toXml()
{
QDomImplementation implementation;
QDomDocumentType docType = implementation.createDocumentType(
"scribe-document", "scribe", "qt,nokia.com/scribe");
document = new QDomDocument(docType);
// ### This processing instruction is required to ensure that any kind
// of encoding is given when the document is written.
QDomProcessingInstruction process = document->createProcessingInstruction(
"xml", "version=\"1.0\" encoding=\"utf-8\"");
document->appendChild(process);
QDomElement documentElement = document->createElement("document");
document->appendChild(documentElement);
QTextFrame *root = textDocument->rootFrame();
if (root)
processFrame(documentElement, root);
return document;
}
void XmlWriter::processBlock(QDomElement &parent, const QTextBlock &block)
{
QDomElement blockElement = document->createElement("block");
blockElement.setAttribute("position", block.position());
blockElement.setAttribute("length", block.length());
parent.appendChild(blockElement);
QTextBlock::iterator it;
for (it = block.begin(); !(it.atEnd()); ++it) {
QTextFragment fragment = it.fragment();
if (fragment.isValid()) {
QDomElement fragmentElement = document->createElement("fragment");
blockElement.appendChild(fragmentElement);
fragmentElement.setAttribute("length", fragment.length());
QDomText fragmentText = document->createTextNode(fragment.text());
fragmentElement.appendChild(fragmentText);
}
}
}
void XmlWriter::processFrame(QDomElement &parent, QTextFrame *frame)
{
QDomElement frameElement = document->createElement("frame");
frameElement.setAttribute("begin", frame->firstPosition());
frameElement.setAttribute("end", frame->lastPosition());
parent.appendChild(frameElement);
QTextFrame::iterator it;
for (it = frame->begin(); !(it.atEnd()); ++it) {
QTextFrame *childFrame = it.currentFrame();
QTextBlock childBlock = it.currentBlock();
if (childFrame) {
QTextTable *childTable = qobject_cast<QTextTable*>(childFrame);
if (childTable)
processTable(frameElement, childTable);
else
processFrame(frameElement, childFrame);
} else if (childBlock.isValid())
processBlock(frameElement, childBlock);
}
}
void XmlWriter::processTable(QDomElement &parent, QTextTable *table)
{
QDomElement element = document->createElement("table");
for (int row = 0; row < table->rows(); ++row) {
for (int column = 0; column < table->columns(); ++column) {
QTextTableCell cell = table->cellAt(row, column);
processTableCell(element, cell);
}
}
parent.appendChild(element);
}
void XmlWriter::processTableCell(QDomElement &parent, const QTextTableCell &cell)
{
QDomElement element = document->createElement("cell");
element.setAttribute("row", cell.row());
element.setAttribute("column", cell.column());
QTextFrame::iterator it;
for (it = cell.begin(); !(it.atEnd()); ++it) {
QTextFrame *childFrame = it.currentFrame();
QTextBlock childBlock = it.currentBlock();
if (childFrame)
processFrame(element, childFrame);
else if (childBlock.isValid())
processBlock(element, childBlock);
}
parent.appendChild(element);
}
#ifndef WINDOW_H
#define WINDOW_H
#include <QMainWindow>
class QTextEdit;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
public slots:
void saveFile();
void showTable();
private:
bool writeXml(const QString &fileName);
QTextEdit *editor;
};
#endif
#include <QtGui>
#include "mainwindow.h"
#include "xmlwriter.h"
MainWindow::MainWindow()
{
QMenu *fileMenu = new QMenu(tr("&File"));
QAction *saveAction = fileMenu->addAction(tr("&Save..."));
saveAction->setShortcut(tr("Ctrl+S"));
QAction *quitAction = fileMenu->addAction(tr("E&xit"));
quitAction->setShortcut(tr("Ctrl+Q"));
QMenu *showMenu = new QMenu(tr("&Show"));
QAction *showTableAction = showMenu->addAction(tr("&Table"));
menuBar()->addMenu(fileMenu);
menuBar()->addMenu(showMenu);
editor = new QTextEdit();
QTextCursor cursor(editor->textCursor());
cursor.movePosition(QTextCursor::Start);
int rows = 11;
int columns = 4;
QTextTableFormat tableFormat;
tableFormat.setBackground(QColor("#e0e0e0"));
QVector<QTextLength> constraints;
constraints << QTextLength(QTextLength::PercentageLength, 16);
constraints << QTextLength(QTextLength::PercentageLength, 28);
constraints << QTextLength(QTextLength::PercentageLength, 28);
constraints << QTextLength(QTextLength::PercentageLength, 28);
tableFormat.setColumnWidthConstraints(constraints);
QTextTable *table = cursor.insertTable(rows, columns, tableFormat);
int column;
int row;
QTextTableCell cell;
QTextCursor cellCursor;
QTextCharFormat charFormat;
charFormat.setForeground(Qt::black);
cell = table->cellAt(0, 0);
cellCursor = cell.firstCursorPosition();
cellCursor.insertText(tr("Week"), charFormat);
for (column = 1; column < columns; ++column) {
cell = table->cellAt(0, column);
cellCursor = cell.firstCursorPosition();
cellCursor.insertText(tr("Team %1").arg(column), charFormat);
}
for (row = 1; row < rows; ++row) {
cell = table->cellAt(row, 0);
cellCursor = cell.firstCursorPosition();
cellCursor.insertText(tr("%1").arg(row), charFormat);
for (column = 1; column < columns; ++column) {
if ((row-1) % 3 == column-1) {
cell = table->cellAt(row, column);
QTextCursor cellCursor = cell.firstCursorPosition();
cellCursor.insertText(tr("On duty"), charFormat);
}
}
}
connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));
connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
connect(showTableAction, SIGNAL(triggered()), this, SLOT(showTable()));
setCentralWidget(editor);
setWindowTitle(tr("Text Document Tables"));
}
void MainWindow::saveFile()
{
QString fileName = QFileDialog::getSaveFileName(this,
tr("Save document as:"), "", tr("XML (*.xml)"));
if (!fileName.isEmpty()) {
if (writeXml(fileName))
setWindowTitle(fileName);
else
QMessageBox::warning(this, tr("Warning"),
tr("Failed to save the document."), QMessageBox::Cancel,
QMessageBox::NoButton);
}
}
void MainWindow::showTable()
{
QTextCursor cursor = editor->textCursor();
QTextTable *table = cursor.currentTable();
if (!table)
return;
QTableWidget *tableWidget = new QTableWidget(table->rows(), table->columns());
for (int row = 0; row < table->rows(); ++row) {
for (int column = 0; column < table->columns(); ++column) {
QTextTableCell tableCell = table->cellAt(row, column);
QTextFrame::iterator it;
QString text;
for (it = tableCell.begin(); !(it.atEnd()); ++it) {
QTextBlock childBlock = it.currentBlock();
if (childBlock.isValid())
text += childBlock.text();
}
QTableWidgetItem *newItem = new QTableWidgetItem(text);
tableWidget->setItem(row, column, newItem);
/*
processTableCell(tableCell);
*/
}
}
tableWidget->setWindowTitle(tr("Table Contents"));
tableWidget->show();
}
bool MainWindow::writeXml(const QString &fileName)
{
XmlWriter documentWriter(editor->document());
QDomDocument *domDocument = documentWriter.toXml();
QFile file(fileName);
if (file.open(QFile::WriteOnly)) {
QTextStream textStream(&file);
textStream.setCodec(QTextCodec::codecForName("UTF-8"));
textStream << domDocument->toString(1).toUtf8();
file.close();
return true;
}
else
return false;
}
#include <QtGui>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow *window = new MainWindow;
window->resize(480, 480);
window->show();
return app.exec();
}
Save created xml document to a file
Foundations of Qt Development\Chapter08\xmldommodify\main.cpp
/*
* Copyright (c) 2006-2007, Johan Thelin
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of APress nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <QFile>
#include <QTextStream>
#include <QDomDocument>
#include <QDomElement>
#include <QDomText>
int main( int argc, char **argv )
{
QFile inFile( "simple.xml" );
if( !inFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
qDebug( "Failed to open file for reading." );
return 0;
}
QDomDocument document;
if( !document.setContent( &inFile ) )
{
qDebug( "Failed to parse the file into a DOM tree." );
inFile.close();
return 0;
}
inFile.close();
QDomElement documentElement = document.documentElement();
QDomNodeList elements = documentElement.elementsByTagName( "bar" );
if( elements.size() == 0 )
{
QDomElement bar = document.createElement( "bar" );
documentElement.insertBefore( bar, QDomNode() );
}
else if( elements.size() == 1 )
{
QDomElement bar = elements.at(0).toElement();
QDomElement baz = document.createElement( "baz" );
baz.setAttribute( "count", QString::number( bar.elementsByTagName( "baz" ).size() + 1 ) );
bar.appendChild( baz );
}
QFile outFile( "simple-modified.xml" );
if( !outFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
{
qDebug( "Failed to open file for writing." );
return 0;
}
QTextStream stream( &outFile );
stream << document.toString();
outFile.close();
return 0;
}