Редактирование: Qt:Документация 4.3.2/qtxml

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск
Внимание: Вы не представились системе. Ваш IP-адрес будет записан в историю изменений этой страницы.

ПРЕДУПРЕЖДЕНИЕ: Длина этой страницы составляет 38 килобайт. Страницы, размер которых приближается к 32 КБ или превышает это значение, могут неверно отображаться в некоторых браузерах. Пожалуйста, рассмотрите вариант разбиения страницы на меньшие части.

Правка может быть отменена. Пожалуйста, просмотрите сравнение версий, чтобы убедиться, что это именно те изменения, которые вас интересуют, и нажмите «Записать страницу», чтобы изменения вступили в силу.
Текущая версия Ваш текст
Строка 1: Строка 1:
{{Qt4.3.2_header}}
{{Qt4.3.2_header}}
-
[Предыдущая: [[Qt:Документация 4.3.2/qtscript | Модуль QtScript]] ] [ [[Qt:Документация 4.3.2/modules | Модули Qt]] ] [Следующая: [[Qt:Документация 4.3.2/qtdesigner | Модуль QtDesigner]] ]  
+
[Previous: [[Qt:Документация 4.3.2/qtsvg | QtSvg Module]]] [ [[Qt:Документация 4.3.2/modules | Qt's Modules]] ] [Next: [[Qt:Документация 4.3.2/qtdesigner | QtDesigner Module]]]
=Модуль QtXml<br />=
=Модуль QtXml<br />=
-
 
Модуль QtXml обеспечивает работу с потоками чтения и записи XML документов и реализацию их в форме SAX и DOM. [[#details | Далее...]]
Модуль QtXml обеспечивает работу с потоками чтения и записи XML документов и реализацию их в форме SAX и DOM. [[#details | Далее...]]
==Классы==
==Классы==
-
 
{|  width="100%" class="annotated" cellpadding="2" cellspacing="1" border="0"
{|  width="100%" class="annotated" cellpadding="2" cellspacing="1" border="0"
Строка 126: Строка 124:
|Запись XML с простым потоковым API
|Запись XML с простым потоковым API
|}
|}
-
<div id="details"></div>
+
 
==Подробное описание==
==Подробное описание==
 +
SAX is an event-based standard interface for XML parsers. The Qt interface follows the design of the SAX2 Java implementation. Its naming scheme was adapted to fit the Qt naming conventions. Details on SAX2 can be found at [http://www.saxproject.org http://www.saxproject.org].
-
SAX это стандартный, основанный на событиях интерфейс для XML парсеров. Qt интерфейс соответствует возможностям SAX2 Java. Его схема именования была адаптирована согласно соглашений именования, принятых в Qt. Подробное описание SAX2 может быть найдено на [http://www.saxproject.org http://www.saxproject.org].
+
Support for SAX2 filters and the reader factory are under development. The Qt implementation does not include the SAX1 compatibility classes present in the Java interface. For an introduction to Qt's SAX2 classes, see [[#the-qt-sax2-classes | The Qt SAX2 Classes]].
-
Поддержка для фильтров SAX2 и reader factory находятся в стадии разработки. Данная версия Qt не обеспечивает совместимости с классами SAX1, представленными в Java интерфейсе. Введение в классы Qt SAX2 смотрите на [[#the-qt-sax2-classes | Классы Qt SAX2]].
+
DOM Level 2 is a W3C Recommendation for XML interfaces that maps the constituents of an XML document to a tree structure. The specification of DOM Level 2 can be found at [http://www.w3.org/DOM/ http://www.w3.org/DOM/]. For more information about the DOM classes in Qt is provided, see [[#the-qt-dom-classes | The Qt DOM Classes]].
-
DOM Level 2 это W3C Recommendation для XML интерфейсов, которые отображают содержание XML документа в виде дерева. Спецификация DOM Level 2 может быть найдена на  [http://www.w3.org/DOM/ http://www.w3.org/DOM/]. Дополнительную информацию о классах DOM в Qt представлена в [[#the-qt-dom-classes | Классы Qt DOM]].
+
Since version 4.3, Qt provides two new classes for reading and writing XML: [[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] and [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]].
-
Начиная с версии 4.3, Qt ввела два новых класса для чтения и записи XML: [[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] и [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]].
+
In addition to core XML support, [[Qt:Документация 4.3.2/qsvgrenderer | QSvgRenderer]] can read a subset of SVG. Additional XML support is provided by the [http://www.trolltech.com/products/qt/addon/solutions/ Qt Solutions] group who provide, for example, classes that support SOAP and MML with the Qt XML classes.
-
Дополнительно возможности XML обеспечивают [[Qt:Документация 4.3.2/qsvgrenderer | QSvgRenderer]] чтение поднабора SVG. Также развитие XML осуществляется группой [http://www.trolltech.com/products/qt/addon/solutions/ Qt Solutions], которая разрабатывает, например, классы для  поддержки SOAP и MML на основе классов Qt XML.
+
To include the definitions of the module's classes, use the following directive:
-
 
+
-
Для подключения модуля с классами нужно использовать следующую директиву:
+
<source lang="cpp-qt"> #include <QtXml></source>  
<source lang="cpp-qt"> #include <QtXml></source>  
-
Чтобы соединиться с модулем добавьте данную строку в ваш [[Qt:Документация 4.3.2/qmake-manual#qmake | qmake]] <tt>.pro</tt> файл:
+
To link against the module, add this line to your [[Qt:Документация 4.3.2/qmake-manual#qmake | qmake]] <tt>.pro</tt> file:
<source lang="cpp-qt"> QT += xml</source>  
<source lang="cpp-qt"> QT += xml</source>  
-
Данный модуль это часть [[Qt:Документация 4.3.2/commercialeditions#qt-console-edition | Qt Console Edition]], [[Qt:Документация 4.3.2/commercialeditions#qt-desktop-edition | Qt Desktop Edition]] и [[Qt:Документация 4.3.2/opensourceedition | Qt Open Source Edition]].
+
This module is part of the [[Qt:Документация 4.3.2/commercialeditions#qt-console-edition | Qt Console Edition]], the [[Qt:Документация 4.3.2/commercialeditions#qt-desktop-edition | Qt Desktop Edition]], and the [[Qt:Документация 4.3.2/opensourceedition | Qt Open Source Edition]].
-
 
+
-
Разделы:
+
-
*[[#configuring-the-build-process | Конфигурирование процесса сборки]]
+
-
*[[#the-qtxml-stream-classes | Классы потока QtXml]]
+
-
*[[#the-qt-sax2-classes | Классы Qt SAX2]]
+
-
**[[#introduction-to-sax2 | Введение в SAX2]]
+
-
**[[#sax2-features | Особенности SAX2]]
+
-
**[[#namespace-support-via-features | Поддержка пространства имен]]
+
-
***[[#summary | Итоги]]
+
-
**[[#properties | Свойства]]
+
-
*[[#the-qt-dom-classes | Классы Qt DOM]]
+
-
**[[#introduction-to-dom | Введение в DOM]]
+
-
*[[#an-introduction-to-namespaces | Введение в пространство имен]]
+
-
**[[#conventions-used-in-the-qt-xml-documentation | Соглашения, используемые в документации Qt XML]]
+
-
<div id="configuring-the-build-process"></div>
+
===Configuring the Build Process===
-
===Конфигурирование процесса сборки===
+
Applications that use Qt's XML classes need to be configured to be built against the QtXml module. The following declaration in a <tt>qmake</tt> project file ensures that an application is compiled and linked appropriately:
-
Приложения, использующие классы Qt XML, должны быть собраны вместе с модулем QtXml. Следующее объявление в <tt>qmake</tt> файла проекта гарантирует, что приложение скомпилируется и отредактируется (linked) соответствующим образом:
+
<source lang="cpp-qt"> QT += xml</source>  
<source lang="cpp-qt"> QT += xml</source>  
-
Данная строка необходима, поскольку только модули [[Qt:Документация 4.3.2/qtcore | QtCore]] и [[Qt:Документация 4.3.2/qtgui | QtGui]] используются по умолчанию в процессе сборки.
+
This line is necessary because only the [[Qt:Документация 4.3.2/qtcore | QtCore]] and [[Qt:Документация 4.3.2/qtgui | QtGui]] modules are used in the default build process.
-
<div id="the-qtxml-stream-classes"></div>
+
-
===Классы потока QtXml===
+
===The QtXml Stream Classes===
-
[[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] и [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]] это два новых класса, появившихся начиная с версии Qt 4.3. Потоковый модуль чтения представляет XML документ как поток токенов (tokens). Это отличие от SAX, т.к. SAX приложения обеспечивают обработку поступающих событий XML от парсера, тогда как [[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] передача осуществляется циклически, втягивая токены из модуля чтения, когда они требуются. Данный подход, основанный на втягивании, предоставляет возможность строить парсеры с рекурсивной обработкой, позволяя разделить код, выполняющий синтаксический анализ XML, на различные методы и классы.
+
The [[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] and [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]] are two new classes provided in Qt 4.3 and later. A stream reader reports an XML document as a stream of tokens. This differs from SAX as SAX applications provide handlers to receive XML events from the parser whereas the [[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] drives the loop, pulling tokens from the reader when they are needed. This pulling approach makes it possible to build recursive descent parsers, allowing XML parsing code to be split into different methods or classes.
-
[[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] это парсеры, обеспечивающие обработку правильных (well-formed) XML документов, за исключением внешних сущностей. Следовательно, данные обрабатываемые потоковым модулем чтения удовлетворяют критерию W3C для правильных (well-formed) XML, что позволит избежать ошибок. С другой стороны, такие функции как [[Qt:Документация 4.3.2/qxmlstreamreader#atEnd | atEnd()]], [[Qt:Документация 4.3.2/qxmlstreamreader#error | error()]] и [[Qt:Документация 4.3.2/qxmlstreamreader#hasError | hasError()]] могут быть использованы для проверки и отображения ошибок.
+
[[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] is a well-formed XML 1.0 parser that excludes external parsed entities. Hence, data provided by the stream reader adheres to the W3C's criteria for well-formed XML, as long as no error occurs. Otherwise, functions such as [[Qt:Документация 4.3.2/qxmlstreamreader#atEnd | atEnd()]], [[Qt:Документация 4.3.2/qxmlstreamreader#error | error()]] and [[Qt:Документация 4.3.2/qxmlstreamreader#hasError | hasError()]] can be used to check and view the errors.
-
Примером использования [[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] может быть <tt>XbelReader</tt> в [[Qt:Документация 4.3.2/xml-streambookmarks | QXmlStream Bookmarks Example]], который является подклассом QXmlStreamReder. Конструктор принимает ''treeWidget'' в качестве параметра и класс получает доступ к специфическим функциям Xbel:
+
An example of [[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] implementation would be the <tt>XbelReader</tt> in [[Qt:Документация 4.3.2/xml-streambookmarks | QXmlStream Bookmarks Example]], which is a subclass of QXmlStreamReder. The constructor takes ''treeWidget'' as a parameter and the class has Xbel specific functions:
<source lang="cpp-qt">    XbelReader(QTreeWidget *treeWidget);
<source lang="cpp-qt">    XbelReader(QTreeWidget *treeWidget);
     ...
     ...
Строка 185: Строка 166:
     QTreeWidget *treeWidget;
     QTreeWidget *treeWidget;
     ...</source>  
     ...</source>  
-
Функция <tt>read()</tt> принимает [[Qt:Документация 4.3.2/qiodevice | QIODevice]] и пердает его в [[Qt:Документация 4.3.2/qxmlstreamreader#setDevice | setDevice()]]. Функция [[Qt:Документация 4.3.2/qxmlstreamreader#raiseError | raiseError()]] используется для отображения пользовательских сообщений об ошибках, показывая, что версия файла некорректна.  
+
The <tt>read()</tt> function accepts a [[Qt:Документация 4.3.2/qiodevice | QIODevice]] and sets it with [[Qt:Документация 4.3.2/qxmlstreamreader#setDevice | setDevice()]]. The [[Qt:Документация 4.3.2/qxmlstreamreader#raiseError | raiseError()]] function is used to display a custom error message, inidicating that the file's version is incorrect.
<source lang="cpp-qt"> bool XbelReader::read(QIODevice *device)
<source lang="cpp-qt"> bool XbelReader::read(QIODevice *device)
  {
  {
Строка 197: Строка 178:
                 readXBEL();
                 readXBEL();
             else
             else
-
                 raiseError(QObject::tr("Файл не является файлом XBEL версии 1.0."));
+
                 raiseError(QObject::tr("The file is not an XBEL version 1.0 file."));
         }
         }
     }
     }
Строка 203: Строка 184:
     return !error();
     return !error();
  }</source>  
  }</source>  
-
Дополнением к [[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] является [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]]. Он представляет собой модуль записи XML с простым потоковым API. [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]] функционирует на основе [[Qt:Документация 4.3.2/qiodevice | QIODevice]]. Он включает специальные функции для токенов или событий XML, которые вы хотите записать. Это [[Qt:Документация 4.3.2/qxmlstreamwriter#writeDTD | writeDTD()]], [[Qt:Документация 4.3.2/qxmlstreamwriter#writeCharacters | writeCharacters()]], [[Qt:Документация 4.3.2/qxmlstreamwriter#writeComment | writeComment()]] и т.д.
+
The pendent to [[Qt:Документация 4.3.2/qxmlstreamreader | QXmlStreamReader]] is [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]], which provides an XML writer with a simple streaming API. [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]] operates on a [[Qt:Документация 4.3.2/qiodevice | QIODevice]] and has specialised functions for all XML tokens or events you want to write, such as [[Qt:Документация 4.3.2/qxmlstreamwriter#writeDTD | writeDTD()]], [[Qt:Документация 4.3.2/qxmlstreamwriter#writeCharacters | writeCharacters()]], [[Qt:Документация 4.3.2/qxmlstreamwriter#writeComment | writeComment()]] and so on.
-
Для того, чтобы записать XML документ с помощью [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]], документ должен начинаться с функции [[Qt:Документация 4.3.2/qxmlstreamwriter#writeStartDocument | writeStartDocument()]] и заканчиваться функцией [[Qt:Документация 4.3.2/qxmlstreamwriter#writeEndDocument | writeEndDocument()]], которая закроет все оставшиеся открытые теги. Теги элементов открываются [[Qt:Документация 4.3.2/qxmlstreamwriter#writeStartDocument | writeStartDocument()]], далее следуют [[Qt:Документация 4.3.2/qxmlstreamwriter#writeAttribute | writeAttribute()]] или [[Qt:Документация 4.3.2/qxmlstreamwriter#writeAttributes | writeAttributes()]], содержание элемента и в конце [[Qt:Документация 4.3.2/qxmlstreamwriter#writeEndDocument | writeEndDocument()]]. Для записи пустого элемента может быть использован [[Qt:Документация 4.3.2/qxmlstreamwriter#writeEmptyElement | writeEmptyElement()]].
+
To write XML document with [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]], you start a document with the [[Qt:Документация 4.3.2/qxmlstreamwriter#writeStartDocument | writeStartDocument()]] function and end it with [[Qt:Документация 4.3.2/qxmlstreamwriter#writeEndDocument | writeEndDocument()]], which implicitly closes all remaining open tags. Element tags are opened with [[Qt:Документация 4.3.2/qxmlstreamwriter#writeStartDocument | writeStartDocument()]] and followed by [[Qt:Документация 4.3.2/qxmlstreamwriter#writeAttribute | writeAttribute()]] or [[Qt:Документация 4.3.2/qxmlstreamwriter#writeAttributes | writeAttributes()]], element content, and then [[Qt:Документация 4.3.2/qxmlstreamwriter#writeEndDocument | writeEndDocument()]]. Also, [[Qt:Документация 4.3.2/qxmlstreamwriter#writeEmptyElement | writeEmptyElement()]] can be used to write empty elements.
-
Содержание элемента представляет собой набор символов, ссылки на сущности или вложенные элементы. Содержание может быть записано  посредством [[Qt:Документация 4.3.2/qxmlstreamwriter#writeCharacters | writeCharacters()]], которая также удаляет запрещённые символы и символьные последовательности, [[Qt:Документация 4.3.2/qxmlstreamwriter#writeEntityReference | writeEntityReference()]] , или последующими вызовами к [[Qt:Документация 4.3.2/qxmlstreamwriter#writeStartElement | writeStartElement()]].
+
Element content comprises characters, entity references or nested elements. Content can be written with [[Qt:Документация 4.3.2/qxmlstreamwriter#writeCharacters | writeCharacters()]], a function that also takes care of escaping all forbidden characters and character sequences, [[Qt:Документация 4.3.2/qxmlstreamwriter#writeEntityReference | writeEntityReference()]], or subsequent calls to [[Qt:Документация 4.3.2/qxmlstreamwriter#writeStartElement | writeStartElement()]].
-
Класс <tt>XbelWriter</tt> из [[Qt:Документация 4.3.2/xml-streambookmarks | QXmlStream Bookmarks Example]] является подклассом [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]]. Его функция <tt>writeFile()</tt> представляет базовые функции [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]], которые упоминались выше:
+
The <tt>XbelWriter</tt> class from [[Qt:Документация 4.3.2/xml-streambookmarks | QXmlStream Bookmarks Example]] is a subclass of [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]]. Its <tt>writeFile()</tt> function illustrates the core functions of [[Qt:Документация 4.3.2/qxmlstreamwriter | QXmlStreamWriter]] mentioned above:
<source lang="cpp-qt"> bool XbelWriter::writeFile(QIODevice *device)
<source lang="cpp-qt"> bool XbelWriter::writeFile(QIODevice *device)
  {
  {
Строка 223: Строка 204:
     writeEndDocument();
     writeEndDocument();
     return true;
     return true;
-
  }</source> <div id="the-qt-sax2-classes"></div>
+
  }</source>  
-
 
+
===The Qt SAX2 Classes===
-
===Классы Qt SAX2===
+
====Introduction to SAX2====
-
<div id="introduction-to-sax2"></div>
+
The SAX2 interface is an event-driven mechanism to provide the user with document information. An "event" in this context means something reported by the parser, for example, it has encountered a start tag, or an end tag, etc.
-
====Введение в SAX2====
+
-
 
+
-
Интерфейс SAX2 - это механизм основанный на событиях для представления пользователю информации документа. В данном контексте "событие" ("event") это реакция парсера, например, на его встречу с начальным или конечным тегом.
+
-
Для большей конкретики давайте рассмотрим следующий пример:
+
To make it less abstract consider the following example:
<source lang="cpp-qt"> <quote>A quotation.</quote></source>  
<source lang="cpp-qt"> <quote>A quotation.</quote></source>  
-
В процессе чтения (парсер SAX2 обычно называют читающий парсер ("reader")) представленного выше документа произойдет три события:
+
Whilst reading (a SAX2 parser is usually referred to as "reader") the above document three events would be triggered:
-
#Встретится начальный тег (<tt><quote></tt>).
+
#A start tag occurs (<tt><quote></tt>).
-
#Обнаружены символьные данные (т.е. текст), "A quotation.".
+
#Character data (i.e&#x2e; text) is found, "A quotation."&#x2e;
-
#Обработан конечный тег (<tt></quote></tt>).
+
#An end tag is parsed (<tt></quote></tt>).
-
Каждый раз, когда произойдет одно из событий парсер отреагирует на него. Вы можете установить обработчик событий для их перехвата.
+
Each time such an event occurs the parser reports it; you can set up event handlers to respond to these events.
-
Представленный подход обеспечивает быстрое чтение XML документа, однако его обработка достаточно трудоемка, поскольку данные не сохраняются в памяти. Они последовательно обрабатываются и отбрасываются. [[#dom | Интерфейс DOM]] читает и сохраняет весь документ, представляя его в виде дерева. Этот подход требует больше памяти, но позволяет более легко обрабатывать документ.
+
Whilst this is a fast and simple approach to read XML documents, manipulation is difficult because data is not stored, simply handled and discarded serially. The [[#dom | DOM interface]] reads in and stores the whole document in a tree structure; this takes more memory, but makes it easier to manipulate the document's structure..
-
Модуль Qt XML включает абстрактный класс, [[Qt:Документация 4.3.2/qxmlreader | QXmlReader]]. Он определяет интерфейс для потенциальной программы чтения согласно SAX2. Qt включает и собственный модуль чтения [[Qt:Документация 4.3.2/qxmlsimplereader | QXmlSimpleReader]], который легко адаптируется посредством подклассов.
+
The Qt XML module provides an abstract class, [[Qt:Документация 4.3.2/qxmlreader | QXmlReader]], that defines the interface for potential SAX2 readers. Qt includes a reader implementation, [[Qt:Документация 4.3.2/qxmlsimplereader | QXmlSimpleReader]], that is easy to adapt through subclassing.
-
Модуль чтения во время синтаксического анализа реагирует на события через специальные классы обработки:
+
The reader reports parsing events through special handler classes:
{|  width="100%" class="annotated" cellpadding="2" cellspacing="1" border="0"
{|  width="100%" class="annotated" cellpadding="2" cellspacing="1" border="0"
|- valign="top" class="qt-style" |  
|- valign="top" class="qt-style" |  
-
!Класс обработки
+
!Handler class
-
!Описание
+
!Description
|- valign="top" class="odd" |  
|- valign="top" class="odd" |  
|[[Qt:Документация 4.3.2/qxmlcontenthandler | QXmlContentHandler]]
|[[Qt:Документация 4.3.2/qxmlcontenthandler | QXmlContentHandler]]
-
|Обрабатывает события, относящиеся к содержанию документа (т.е. начальный тег или символы).
+
|Reports events related to the content of a document (e.g&#x2e; the start tag or characters).
|- valign="top" class="even" |  
|- valign="top" class="even" |  
|[[Qt:Документация 4.3.2/qxmldtdhandler | QXmlDTDHandler]]
|[[Qt:Документация 4.3.2/qxmldtdhandler | QXmlDTDHandler]]
-
|Обрабатывает события, относящиеся к DTD (т.е. объявления нотаций).
+
|Reports events related to the DTD (e.g&#x2e; notation declarations).
|- valign="top" class="odd" |  
|- valign="top" class="odd" |  
|[[Qt:Документация 4.3.2/qxmlerrorhandler | QXmlErrorHandler]]
|[[Qt:Документация 4.3.2/qxmlerrorhandler | QXmlErrorHandler]]
-
|Обрабатывает ошибки или предупреждения, которые имели место во время синтаксического анализа.
+
|Reports errors or warnings that occurred during parsing.
|- valign="top" class="even" |  
|- valign="top" class="even" |  
|[[Qt:Документация 4.3.2/qxmlentityresolver | QXmlEntityResolver]]
|[[Qt:Документация 4.3.2/qxmlentityresolver | QXmlEntityResolver]]
-
|Обрабатывает внешние сущности и позволяет пользователям сами разрешать внешние сущности вместо тех, что установил модуль чтения.
+
|Reports external entities during parsing and allows users to resolve external entities themselves instead of leaving it to the reader.
|- valign="top" class="odd" |  
|- valign="top" class="odd" |  
|[[Qt:Документация 4.3.2/qxmldeclhandler | QXmlDeclHandler]]
|[[Qt:Документация 4.3.2/qxmldeclhandler | QXmlDeclHandler]]
-
|Обрабатывает иные события, относящиеся к DTD (т.е. объявления атрибутов).
+
|Reports further DTD related events (e.g&#x2e; attribute declarations).
|- valign="top" class="even" |  
|- valign="top" class="even" |  
|[[Qt:Документация 4.3.2/qxmllexicalhandler | QXmlLexicalHandler]]
|[[Qt:Документация 4.3.2/qxmllexicalhandler | QXmlLexicalHandler]]
-
|Обрабатывает события, относящиеся к лексической структуре документа (заголовок DTD, комментарии и т.д.)&#x2e;
+
|Reports events related to the lexical structure of the document (the beginning of the DTD, comments etc.)&#x2e;
|}
|}
-
Данные классы это абстрактные классы описываемого интерфейса. Класс [[Qt:Документация 4.3.2/qxmldefaulthandler | QXmlDefaultHandler]] обеспечивает по умолчанию для всех остальных классов "пустые действия" ("do nothing"). Следовательно пользователям необходимо только перегрузить функции [[Qt:Документация 4.3.2/qxmldefaulthandler | QXmlDefaultHandler]] в зависимости от своих интересов.
+
These classes are abstract classes describing the interface. The [[Qt:Документация 4.3.2/qxmldefaulthandler | QXmlDefaultHandler]] class provides a "do nothing" default implementation for all of them. Therefore users only need to overload the [[Qt:Документация 4.3.2/qxmldefaulthandler | QXmlDefaultHandler]] functions they are interested in.
-
Для чтения входных XML данных используется специальный класс [[Qt:Документация 4.3.2/qxmlinputsource | QXmlInputSource]].
+
To read input XML data a special class [[Qt:Документация 4.3.2/qxmlinputsource | QXmlInputSource]] is used.
 +
 
 +
Apart from those already mentioned, the following SAX2 support classes provide additional useful functionality:
-
Следующие классы поддержки SAX2 обеспечивают дополнительную полезную функциональность. Некоторые из них уже упоминались.
 
{|  width="100%" class="annotated" cellpadding="2" cellspacing="1" border="0"
{|  width="100%" class="annotated" cellpadding="2" cellspacing="1" border="0"
|- valign="top" class="qt-style" |  
|- valign="top" class="qt-style" |  
-
!Класс
+
!Class
-
!Описание
+
!Description
|- valign="top" class="odd" |  
|- valign="top" class="odd" |  
|[[Qt:Документация 4.3.2/qxmlattributes | QXmlAttributes]]
|[[Qt:Документация 4.3.2/qxmlattributes | QXmlAttributes]]
-
|Используется для передачи атрибутов в событие начального элемента.
+
|Used to pass attributes in a start element event.
|- valign="top" class="even" |  
|- valign="top" class="even" |  
|[[Qt:Документация 4.3.2/qxmllocator | QXmlLocator]]
|[[Qt:Документация 4.3.2/qxmllocator | QXmlLocator]]
-
|Используется для получения реальной позиции обработки события.
+
|Used to obtain the actual parsing position of an event.
|- valign="top" class="odd" |  
|- valign="top" class="odd" |  
|[[Qt:Документация 4.3.2/qxmlnamespacesupport | QXmlNamespaceSupport]]
|[[Qt:Документация 4.3.2/qxmlnamespacesupport | QXmlNamespaceSupport]]
-
|Используется с целью поддержки пространства имен в модуле чтения. Отметим, сто пространства имен не изменяют алгоритм обработки. Они только отображаются в обработчике.
+
|Used to implement namespace support for a reader. Note that namespaces do not change the parsing behavior. They are only reported through the handler.
|}
|}
-
[[Qt:Документация 4.3.2/xml-saxbookmarks | Пример SAX Bookmarks]] показывает как в подклассе [[Qt:Документация 4.3.2/qxmldefaulthandler | QXmlDefaultHandler]] выполняется чтение XML bookmark файла (XBEL) и как генерировать XML вручную.
+
The [[Qt:Документация 4.3.2/xml-saxbookmarks | SAX Bookmarks example]] illustrates how to subclass [[Qt:Документация 4.3.2/qxmldefaulthandler | QXmlDefaultHandler]] to read an XML bookmark file (XBEL) and how to generate XML by hand.
-
<div id="sax2-features"></div>
+
-
 
+
-
====Особенности SAX2====
+
-
Поведение модуля чтения (reader) XML зависит от того, как он поддерживает ряд необязательных опций. Например, модуль чтения может иметь возможность "выдача атрибутов, используемых для объявления префикса пространства имен и связывания префикса с локальным именем тега". Подобно другим, данная возможность имеет уникальное имя, представленное URI: ''http://xml.org/sax/features/namespace-prefixes''.
+
====SAX2 Features====
 +
The behavior of an XML reader depends on its support for certain optional features. For example, a reader may have the feature "report attributes used for namespace declarations and prefixes along with the local name of a tag". Like every other feature this has a unique name represented by a URI: it is called ''http://xml.org/sax/features/namespace-prefixes''.
-
Реализация  SAX2 в Qt позволяет определить, может ли модуль чтения иметь не стандартную функциональность . Для этого используется функция [[Qt:Документация 4.3.2/qxmlreader#hasFeature | QXmlReader::hasFeature]](). Доступные особенности могут определяться с помощью [[Qt:Документация 4.3.2/qxmlreader#feature | QXmlReader::feature]](). Их можно включать и отключать используя [[Qt:Документация 4.3.2/qxmlreader#setFeature | QXmlReader::setFeature]]().
+
The Qt SAX2 implementation can report whether the reader has particular functionality using the [[Qt:Документация 4.3.2/qxmlreader#hasFeature | QXmlReader::hasFeature]]() function. Available features can be tested with [[Qt:Документация 4.3.2/qxmlreader#feature | QXmlReader::feature]](), and switched on or off using [[Qt:Документация 4.3.2/qxmlreader#setFeature | QXmlReader::setFeature]]().
-
Возьмем следующий пример
+
Consider the example
<source lang="cpp-qt"> <document xmlns:book = 'http://trolltech.com/fnord/book/'
<source lang="cpp-qt"> <document xmlns:book = 'http://trolltech.com/fnord/book/'
           xmlns      = 'http://trolltech.com/fnord/' ></source>  
           xmlns      = 'http://trolltech.com/fnord/' ></source>  
-
Модуль чтения, который не поддерживает опцию ''http://xml.org/sax/features/namespace-prefixes'' будет выдавать имя элемента ''document'', но без его атрибутов ''xmlns:book'' и ''xmlns'' и их значений. Модуль чтения с поддержкой опции ''http://xml.org/sax/features/namespace-prefixes'' выдаст атрибуты пространства имен, если [[Qt:Документация 4.3.2/qxmlreader#feature | feature]] включен.
+
A reader that does not support the ''http://xml.org/sax/features/namespace-prefixes'' feature would report the element name ''document'' but not its attributes ''xmlns:book'' and ''xmlns'' with their values. A reader with the feature ''http://xml.org/sax/features/namespace-prefixes'' reports the namespace attributes if the [[Qt:Документация 4.3.2/qxmlreader#feature | feature]] is switched on.
-
Другие особенности включают ''http://xml.org/sax/features/namespace'' (обработка пространства имен, полагая ''http://xml.org/sax/features/namespace-prefixes'') и  ''http://xml.org/sax/features/validation'' (способность выдавать ошибки проверки на соответствие схеме).
+
Other features include ''http://xml.org/sax/features/namespace'' (namespace processing, implies ''http://xml.org/sax/features/namespace-prefixes'') and ''http://xml.org/sax/features/validation'' (the ability to report validation errors).
-
В том случае, если SAX2 предоставляет возможность пользователю задавать и выполнять требуемые особенности, поддержка ''http://xml.org/sax/features/namespace'' (а также ''http://xml.org/sax/features/namespace-prefixes'') обязательна. Функциональность [[Qt:Документация 4.3.2/qxmlsimplereader | QXmlSimpleReader]] из [[Qt:Документация 4.3.2/qxmlreader | QXmlReader]], поддерживает их, и позволяя обрабатывать пространства имен.
+
Whilst SAX2 leaves it to the user to define and implement whatever features are required, support for ''http://xml.org/sax/features/namespace'' (and thus ''http://xml.org/sax/features/namespace-prefixes'') is mandantory. The [[Qt:Документация 4.3.2/qxmlsimplereader | QXmlSimpleReader]] implementation of [[Qt:Документация 4.3.2/qxmlreader | QXmlReader]], supports them, and can do namespace processing.
-
[[Qt:Документация 4.3.2/qxmlsimplereader | QXmlSimpleReader]] не проверяет на соответствие схеме, поскольку он не поддерживает ''http://xml.org/sax/features/validation''.
+
[[Qt:Документация 4.3.2/qxmlsimplereader | QXmlSimpleReader]] is not validating, so it does not support ''http://xml.org/sax/features/validation''.
-
<div id="namespace-support-via-features"></div>
+
-
====Поддержка пространства имен посредством опций====
+
====Namespace Support via Features====
 +
As we have seen in the previous section, we can configure the behavior of the reader when it comes to namespace processing. This is done by setting and unsetting the ''http://xml.org/sax/features/namespaces'' and ''http://xml.org/sax/features/namespace-prefixes'' features.
-
Как показано в предыдущем разделе, мы можем конфигурировать правила работы модуля чтения, когда он получает управление для обработки пространства имен. Это выполняется посредством задания и отключения опций ''http://xml.org/sax/features/namespaces'' и ''http://xml.org/sax/features/namespace-prefixes''.
+
They influence the reporting behavior in the following way:
-
Они влияют на алгоритм поведения в следующих случаях:
+
#Namespace prefixes and local parts of elements and attributes can be reported.
 +
#The qualified names of elements and attributes are reported.
 +
#[[Qt:Документация 4.3.2/qxmlcontenthandler#startPrefixMapping | QXmlContentHandler::startPrefixMapping]]() and [[Qt:Документация 4.3.2/qxmlcontenthandler#endPrefixMapping | QXmlContentHandler::endPrefixMapping]]() are called by the reader.
 +
#Attributes that declare namespaces (i.e&#x2e; the attribute ''xmlns'' and attributes starting with ''xmlns:'') are reported.
-
#При отображении префиксов пространств имен и локальных частей элементов и атрибутов.
+
Consider the following element:
-
#При отображении квалификационных имен элементов и атрибутов.
+
-
#При вызове модулем чтения [[Qt:Документация 4.3.2/qxmlcontenthandler#startPrefixMapping | QXmlContentHandler::startPrefixMapping]]() и [[Qt:Документация 4.3.2/qxmlcontenthandler#endPrefixMapping | QXmlContentHandler::endPrefixMapping]]().
+
-
#При отображении атрибутов, которые объявляют пространства имен (т.е. атрибута ''xmlns'' и атрибутов, начинающиеся с ''xmlns:'').
+
-
 
+
-
Возьмем следующий элемент:
+
<source lang="cpp-qt"> <author xmlns:fnord = 'http://trolltech.com/fnord/'
<source lang="cpp-qt"> <author xmlns:fnord = 'http://trolltech.com/fnord/'
               title="Ms"
               title="Ms"
               fnord:title="Goddess"
               fnord:title="Goddess"
               name="Eris Kallisti"/></source>  
               name="Eris Kallisti"/></source>  
-
Если установить ''http://xml.org/sax/features/namespace-prefixes'' в true, то модуль чтения будет отображать четыре атирибута; но установив опцию ''namespace-prefixes'' в false только три. Атрибут ''xmlns:fnord'', определяющий пространство имен "невидим" для модуля чтения.
+
With ''http://xml.org/sax/features/namespace-prefixes'' set to true the reader will report four attributes; but with the ''namespace-prefixes'' feature set to false only three, with the ''xmlns:fnord'' attribute defining a namespace being "invisible" to the reader.
-
Опция ''http://xml.org/sax/features/namespaces'' отвечает за видимость локальных имен, префиксов пространства имен и URI. В случае установки ''http://xml.org/sax/features/namespaces'' в true, парсер отобразит ''title'' как локальное имя атрибута ''fnord:title'', ''fnord'' как префикс пространства имен и ''http://trolltech.com/fnord/'' как URI пространства имен. Когда ''http://xml.org/sax/features/namespaces'' установлен в  false они не будут отображаться.
+
The ''http://xml.org/sax/features/namespaces'' feature is responsible for reporting local names, namespace prefixes and URIs. With ''http://xml.org/sax/features/namespaces'' set to true the parser will report ''title'' as the local name of the ''fnord:title'' attribute, ''fnord'' being the namespace prefix and ''http://trolltech.com/fnord/'' as the namespace URI. When ''http://xml.org/sax/features/namespaces'' is false none of them are reported.
-
В текущей версии классов Qt XML определено, что префикс ''xmlns'' самостоятельно не сопоставляется ни с каким пространством имен (см. [http://www.w3.org/TR/1999/REC-xml-names-19990114/#ns-using http://www.w3.org/TR/1999/REC-xml-names-19990114/#ns-using]). Следовательно, даже если и ''http://xml.org/sax/features/namespaces'' и ''http://xml.org/sax/features/namespace-prefixes'' установлены в true, модуль чтения не сможет вернуть ни локальное именя, ни префикс пространства имен, ни URI пространства имен для ''xmlns:fnord''.
+
In the current implementation the Qt XML classes follow the definition that the prefix ''xmlns'' itself isn't associated with any namespace at all (see [http://www.w3.org/TR/1999/REC-xml-names-19990114/#ns-using http://www.w3.org/TR/1999/REC-xml-names-19990114/#ns-using]). Therefore even with ''http://xml.org/sax/features/namespaces'' and ''http://xml.org/sax/features/namespace-prefixes'' both set to true the reader won't return either a local name, a namespace prefix or a namespace URI for ''xmlns:fnord''.
-
Возможно это изменится в будущем, когда W3C даст указание [http://www.w3.org/2000/xmlns/ http://www.w3.org/2000/xmlns/] связывать ''xmlns'' с пространством имен ''http://www.w3.org/2000/xmlns''.
+
This might be changed in the future following the W3C suggestion [http://www.w3.org/2000/xmlns/ http://www.w3.org/2000/xmlns/] to associate ''xmlns'' with the namespace ''http://www.w3.org/2000/xmlns''.
-
Стандарт SAX2 предлагает, значение по умолчанию для [[Qt:Документация 4.3.2/qxmlsimplereader | QXmlSimpleReader]] ''http://xml.org/sax/features/namespaces'' установлено в true, а  для ''http://xml.org/sax/features/namespace-prefixes'' в false. Отметим, что комбинация [[Qt:Документация 4.3.2/qxmlsimplereader#setFeature | QXmlSimpleReader::setFeature]](), связанная с установлением обеих опций в false является незаконной.
+
As the SAX2 standard suggests, [[Qt:Документация 4.3.2/qxmlsimplereader | QXmlSimpleReader]] defaults to having ''http://xml.org/sax/features/namespaces'' set to true and ''http://xml.org/sax/features/namespace-prefixes'' set to false. When changing this behavior using [[Qt:Документация 4.3.2/qxmlsimplereader#setFeature | QXmlSimpleReader::setFeature]]() note that the combination of both features set to false is illegal.
-
<div id="summary"></div>
+
-
=====Заключение=====
+
-
[[Qt:Документация 4.3.2/qxmlsimplereader | QXmlSimpleReader]] поддерживает следующие правила:
+
=====Summary=====
 +
[[Qt:Документация 4.3.2/qxmlsimplereader | QXmlSimpleReader]] implements the following behavior:
Строка 348: Строка 322:
|- valign="top" class="qt-style" |  
|- valign="top" class="qt-style" |  
!(namespaces, namespace-prefixes)
!(namespaces, namespace-prefixes)
-
!Префикс пространства имен и локальная часть
+
!Namespace prefix and local part
-
!Квалифицированные имена
+
!Qualified names
-
!Отображение префикса
+
!Prefix mapping
-
!Атрибуты xmlns
+
!xmlns attributes
|- valign="top" class="odd" |  
|- valign="top" class="odd" |  
|(true, false)
|(true, false)
Строка 375: Строка 349:
|}
|}
-
Поведение записей, отмеченных звездочкой (*) не определено в SAX.
+
The behavior of the entries marked with an asterisk (*) is not specified by SAX.
-
<div id="properties"></div>
+
====Свойства====
====Свойства====
-
 
Свойства are a more general concept. They have a unique name, represented as an URI, but their value is <tt>void*</tt>. Thus nearly anything can be used as a property value. This concept involves some danger, though: there is no means of ensuring type-safety; the user must take care that they pass the right type. Свойства are useful if a reader supports special handler classes.
Свойства are a more general concept. They have a unique name, represented as an URI, but their value is <tt>void*</tt>. Thus nearly anything can be used as a property value. This concept involves some danger, though: there is no means of ensuring type-safety; the user must take care that they pass the right type. Свойства are useful if a reader supports special handler classes.
Строка 387: Строка 359:
To set or query properties the following functions are provided: [[Qt:Документация 4.3.2/qxmlreader#setProperty | QXmlReader::setProperty]](), [[Qt:Документация 4.3.2/qxmlreader#property | QXmlReader::property]]() and [[Qt:Документация 4.3.2/qxmlreader#hasProperty | QXmlReader::hasProperty]]().
To set or query properties the following functions are provided: [[Qt:Документация 4.3.2/qxmlreader#setProperty | QXmlReader::setProperty]](), [[Qt:Документация 4.3.2/qxmlreader#property | QXmlReader::property]]() and [[Qt:Документация 4.3.2/qxmlreader#hasProperty | QXmlReader::hasProperty]]().
-
<div id="dom"></div><div id="the-qt-dom-classes"></div>
 
-
===Классы Qt DOM===
+
===The Qt DOM Classes===
-
<div id="domintro"></div><div id="introduction-to-dom"></div>
+
====Introduction to DOM====
-
====Введение в DOM====
+
DOM provides an interface to access and change the content and structure of an XML file. It makes a hierarchical view of the document (a tree view). Thus -- in contrast to the SAX2 interface -- an object model of the document is resident in memory after parsing which makes manipulation easy.
-
DOM представляет интерфейс для доступа или изменения содержания и структуры XML файла. Он формирует иерархическое представление документа (представление в виде дерева). В противоположность интерфейсу SAX2 , объектная модель документа после синтаксического анализа располагается в памяти, что позволяет легко ей манипулировать.  
+
All DOM nodes in the document tree are subclasses of [[Qt:Документация 4.3.2/qdomnode | QDomNode]]. The document itself is represented as a [[Qt:Документация 4.3.2/qdomdocument | QDomDocument]] object.
-
Все узлы DOM в дереве документа являются подклассами [[Qt:Документация 4.3.2/qdomnode | QDomNode]]. Сам документ представляется как объект [[Qt:Документация 4.3.2/qdomdocument | QDomDocument]].
+
Here are the available node classes and their potential child classes:
-
Ниже представлены доступные классы узлов и указано - есть ли у них дочерние классы:
+
*[[Qt:Документация 4.3.2/qdomdocument | QDomDocument]]: возможные дети
-
 
+
**[[Qt:Документация 4.3.2/qdomelement | QDomElement]] (at most one)
-
*[[Qt:Документация 4.3.2/qdomdocument | QDomDocument]]: возможны дочерние классы
+
-
**[[Qt:Документация 4.3.2/qdomelement | QDomElement]] (максимум один)
+
**[[Qt:Документация 4.3.2/qdomprocessinginstruction | QDomProcessingInstruction]]
**[[Qt:Документация 4.3.2/qdomprocessinginstruction | QDomProcessingInstruction]]
**[[Qt:Документация 4.3.2/qdomcomment | QDomComment]]
**[[Qt:Документация 4.3.2/qdomcomment | QDomComment]]
**[[Qt:Документация 4.3.2/qdomdocumenttype | QDomDocumentType]]
**[[Qt:Документация 4.3.2/qdomdocumenttype | QDomDocumentType]]
-
*[[Qt:Документация 4.3.2/qdomdocumentfragment | QDomDocumentFragment]]: возможны дочерние классы
+
*[[Qt:Документация 4.3.2/qdomdocumentfragment | QDomDocumentFragment]]: возможные дети
**[[Qt:Документация 4.3.2/qdomelement | QDomElement]]
**[[Qt:Документация 4.3.2/qdomelement | QDomElement]]
**[[Qt:Документация 4.3.2/qdomprocessinginstruction | QDomProcessingInstruction]]
**[[Qt:Документация 4.3.2/qdomprocessinginstruction | QDomProcessingInstruction]]
Строка 413: Строка 382:
**[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]
**[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]
-
*[[Qt:Документация 4.3.2/qdomdocumenttype | QDomDocumentType]]: нет дочерних классов
+
*[[Qt:Документация 4.3.2/qdomdocumenttype | QDomDocumentType]]: детей нет
-
*[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]: возможны дочерние классы
+
*[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]: возможные дети
**[[Qt:Документация 4.3.2/qdomelement | QDomElement]]
**[[Qt:Документация 4.3.2/qdomelement | QDomElement]]
**[[Qt:Документация 4.3.2/qdomprocessinginstruction | QDomProcessingInstruction]]
**[[Qt:Документация 4.3.2/qdomprocessinginstruction | QDomProcessingInstruction]]
Строка 422: Строка 391:
**[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]
**[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]
-
*[[Qt:Документация 4.3.2/qdomelement | QDomElement]]: возможны дочерние классы
+
*[[Qt:Документация 4.3.2/qdomelement | QDomElement]]: возможные дети
**[[Qt:Документация 4.3.2/qdomelement | QDomElement]]
**[[Qt:Документация 4.3.2/qdomelement | QDomElement]]
**[[Qt:Документация 4.3.2/qdomtext | QDomText]]
**[[Qt:Документация 4.3.2/qdomtext | QDomText]]
Строка 430: Строка 399:
**[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]
**[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]
-
*[[Qt:Документация 4.3.2/qdomattr | QDomAttr]]: возможны дочерние классы
+
*[[Qt:Документация 4.3.2/qdomattr | QDomAttr]]: возможные дети
**[[Qt:Документация 4.3.2/qdomtext | QDomText]]
**[[Qt:Документация 4.3.2/qdomtext | QDomText]]
**[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]
**[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]
-
*[[Qt:Документация 4.3.2/qdomprocessinginstruction | QDomProcessingInstruction]]: нет дочерних классов
+
*[[Qt:Документация 4.3.2/qdomprocessinginstruction | QDomProcessingInstruction]]: детей нет
-
*[[Qt:Документация 4.3.2/qdomcomment | QDomComment]]: возможны дочерние классы
+
*[[Qt:Документация 4.3.2/qdomcomment | QDomComment]]: детей нет
-
*[[Qt:Документация 4.3.2/qdomtext | QDomText]]: нет дочерних классов
+
*[[Qt:Документация 4.3.2/qdomtext | QDomText]]: детей нет
-
*[[Qt:Документация 4.3.2/qdomcdatasection | QDomCDATASection]]: нет дочерних классов
+
*[[Qt:Документация 4.3.2/qdomcdatasection | QDomCDATASection]]: детей нет
-
*[[Qt:Документация 4.3.2/qdomentity | QDomEntity]]: возможны дочерние классы
+
*[[Qt:Документация 4.3.2/qdomentity | QDomEntity]]: возможные дети
**[[Qt:Документация 4.3.2/qdomelement | QDomElement]]
**[[Qt:Документация 4.3.2/qdomelement | QDomElement]]
**[[Qt:Документация 4.3.2/qdomprocessinginstruction | QDomProcessingInstruction]]
**[[Qt:Документация 4.3.2/qdomprocessinginstruction | QDomProcessingInstruction]]
Строка 446: Строка 415:
**[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]
**[[Qt:Документация 4.3.2/qdomentityreference | QDomEntityReference]]
-
*[[Qt:Документация 4.3.2/qdomnotation | QDomNotation]]: нет дочерних классов
+
*[[Qt:Документация 4.3.2/qdomnotation | QDomNotation]]: детей нет
-
[[Qt:Документация 4.3.2/qdomnodelist | QDomNodeList]] и [[Qt:Документация 4.3.2/qdomnamednodemap | QDomNamedNodeMap]] - две коллекции классов, которые обеспечивают: [[Qt:Документация 4.3.2/qdomnodelist | QDomNodeList]] - список узлов, а [[Qt:Документация 4.3.2/qdomnamednodemap | QDomNamedNodeMap]] обработку неупорядоченного набора узлов (часто используется для атрибутов).
+
With [[Qt:Документация 4.3.2/qdomnodelist | QDomNodeList]] and [[Qt:Документация 4.3.2/qdomnamednodemap | QDomNamedNodeMap]] two collection classes are provided: [[Qt:Документация 4.3.2/qdomnodelist | QDomNodeList]] is a list of nodes, and [[Qt:Документация 4.3.2/qdomnamednodemap | QDomNamedNodeMap]] is used to handle unordered sets of nodes (often used for attributes).
-
Класс [[Qt:Документация 4.3.2/qdomimplementation | QDomImplementation]] позволяет пользователю запрашивать особенности обработки DOM.
+
The [[Qt:Документация 4.3.2/qdomimplementation | QDomImplementation]] class allows the user to query features of the DOM implementation.
-
Прежде чем начать работать пожалуйста посмотрите документацию [[Qt:Документация 4.3.2/qdomdocument | QDomDocument]]. Вы также можете захотеть посмотреть [[Qt:Документация 4.3.2/xml-dombookmarks | пример DOM Bookmarks]], который иллюстрирует применение DOM для чтения и записи закладок XML файла (XBEL).
+
To get started please refer to the [[Qt:Документация 4.3.2/qdomdocument | QDomDocument]] documentation. You might also want to take a look at the [[Qt:Документация 4.3.2/xml-dombookmarks | DOM Bookmarks example]], which illustrates how to read and write an XML bookmark file (XBEL) using DOM.
-
<div id="namespaces"></div><div id="an-introduction-to-namespaces"></div>
+
-
===Введение в пространство имен (NameSpace)===
+
===An Introduction to Namespaces===
 +
Parts of the Qt XML module documentation assume that you are familiar with XML namespaces. Here we present a brief introduction; skip to [[#namespacesconventions | Qt XML documentation conventions]] if you already know this material.
-
Часть разделов документации Qt XML module предполагает, что вы знакомы с пространством имен XML. Здесь мы даем краткое введение. Если вы знакомы с [[#namespacesconventions | Qt XML documentation conventions]], то можете пропустить данный материал.
+
Namespaces are a concept introduced into XML to allow a more modular design. With their help data processing software can easily resolve naming conflicts in XML documents.
-
Пространство имен - это концепция, введенная в XML, чтобы позволить осуществлять более модульное проектирование. С его помощью во время программной обработки данных можно легко разрешить конфликты именования имен в XML документах.
+
Consider the following example:
-
 
+
-
Рассмотрим следующий пример:
+
<source lang="cpp-qt"> <document>
<source lang="cpp-qt"> <document>
  <book>
  <book>
Строка 471: Строка 438:
  </book>
  </book>
  </document></source>  
  </document></source>  
-
Здесь можно увидеть три различных использования имени ''title''. Если вы захотите обработать данный документ, то у вас появятся проблемы, поскольку каждый из ''titles'' должен представляться в разной манере, несмотря на то, что используется одно и тоже имя.
+
Here we find three different uses of the name ''title''. If you wish to process this document you will encounter problems because each of the ''titles'' should be displayed in a different manner -- even though they have the same name.
-
Решение должно основываться на неком способе, позволяющем идентифицировать первый  ''title'' как название книги, т.е. использовать элемент ''title'' в пространстве имен книги для отличия его, например, от названия раздела:
+
The solution would be to have some means of identifying the first occurrence of ''title'' as the title of a book, i.e&#x2e; to use the ''title'' element of a book namespace to distinguish it from, for example, the chapter title, e.g&#x2e;:
<source lang="cpp-qt"> <book:title>Practical XML</book:title></source>  
<source lang="cpp-qt"> <book:title>Practical XML</book:title></source>  
-
В данном случае ''book'' является ''префиксом'', указывающим на пространство имен.
+
''book'' in this case is a ''prefix'' denoting the namespace.
-
До того, как применять пространство имен для элементов и атрибутов, необходимо его объявить.
+
Before we can apply a namespace to element or attribute names we must declare it.
-
Пространство имен подобно URI: ''http://trolltech.com/fnord/book/''. Данное URI не указывает, что по этому адресу должны быть доступны данные. URI просто используется для задания уникального имени.
+
Namespaces are URIs like ''http://trolltech.com/fnord/book/''. This does not mean that data must be available at this address; the URI is simply used to provide a unique name.
-
Мы указываем пространства имен точно также как и атрибуты. Строго говоря они и ''есть'' атрибуты. Для того, чтобы объявить пространство имен документа ''http://trolltech.com/fnord/'' как пространство имен по умолчанию, мы должны написать
+
We declare namespaces in the same way as attributes; strictly speaking they ''are'' attributes. To make for example ''http://trolltech.com/fnord/'' the document's default XML namespace ''xmlns'' we write
<source lang="cpp-qt"> xmlns="http://trolltech.com/fnord/"</source>  
<source lang="cpp-qt"> xmlns="http://trolltech.com/fnord/"</source>  
-
Чтобы отличить пространство имен ''http://trolltech.com/fnord/book/'' от пространства имен по умолчанию, мы должны использовать префикс:
+
To distinguish the ''http://trolltech.com/fnord/book/'' namespace from the default, we must supply it with a prefix:
<source lang="cpp-qt"> xmlns:book="http://trolltech.com/fnord/book/"</source>  
<source lang="cpp-qt"> xmlns:book="http://trolltech.com/fnord/book/"</source>  
-
Пространство имен, объявленное таким образом, может быть добавлено к именам элементов и атрибутов посредством префикса и разделителя ":". Мы уже видели это у элемента ''book:title''.
+
A namespace that is declared like this can be applied to element and attribute names by prepending the appropriate prefix and a ":" delimiter. We have already seen this with the ''book:title'' element.
-
Имена элементов без префикса принадлежат пространству имен по умолчанию. Данное правило не распространяется на атрибуты. Атрибут без префикса вообще не принадлежит никакому объявленному пространству имен XML. Атрибуты всегда принадлежат к "традиционному" пространству имен элемента, с которым они применяются. "Традиционное" пространства имен это не пространства имен XML.  Просто предполагается, что все имена атрибутов, принадлежащие одному элементу, должны быть разными. Далее мы увидим как назначается пространство имен XML для атрибута.
+
Element names without a prefix belong to the default namespace. This rule does not apply to attributes: an attribute without a prefix does not belong to any of the declared XML namespaces at all. Attributes always belong to the "traditional" namespace of the element in which they appear. A "traditional" namespace is not an XML namespace, it simply means that all attribute names belonging to one element must be different. Later we will see how to assign an XML namespace to an attribute.
-
Фактически атрибуты без префикса не принадлежат никакому пространству имен XML, при этом нет коллизии между атрибутом ''title'' (который принадлежит элементу ''author'') и, например, элементом ''title'' в контейнере ''chapter''.
+
Due to the fact that attributes without prefixes are not in any XML namespace there is no collision between the attribute ''title'' (that belongs to the ''author'' element) and for example the ''title'' element within a ''chapter''.
-
Давайте проясним это на примере:
+
Let's clarify this with an example:
<source lang="cpp-qt"> <document xmlns:book = 'http://trolltech.com/fnord/book/'
<source lang="cpp-qt"> <document xmlns:book = 'http://trolltech.com/fnord/book/'
           xmlns      = 'http://trolltech.com/fnord/' >
           xmlns      = 'http://trolltech.com/fnord/' >
Строка 505: Строка 472:
  </book>
  </book>
  </document></source>  
  </document></source>  
-
В элементе ''document'' мы имеем два объявления пространства имен. Пространство имен по умолчанию ''http://trolltech.com/fnord/'' применяется к элементу ''book'', элементу ''chapter'', соответствующему элементу ''title'' и, конечно, к самому элементу  ''document''.
+
Within the ''document'' element we have two namespaces declared. The default namespace ''http://trolltech.com/fnord/'' applies to the ''book'' element, the ''chapter'' element, the appropriate ''title'' element and of course to ''document'' itself.
-
Элементы ''book:author'' и ''book:title'' принадлежат пространству имен, идентифицируемому URI ''http://trolltech.com/fnord/book/''.
+
The ''book:author'' and ''book:title'' elements belong to the namespace with the URI ''http://trolltech.com/fnord/book/''.
-
Двум атрибутам ''title'' и ''name'' элемента ''book:author'' не назначено пространство имен XML. Они являются членами "традиционного" пространства имен элемента ''book:author''. Это означает, что, например, два атрибута ''title'' в ''book:author'' недопустимо.
+
The two ''book:author'' attributes ''title'' and ''name'' have no XML namespace assigned. They are only members of the "traditional" namespace of the element ''book:author'', meaning that for example two ''title'' attributes in ''book:author'' are forbidden.
-
Выше в примере мы обошли данное правило. Мы объявили пространство имен ''http://trolltech.com/fnord/'' с префиксом ''fnord'' в элементе ''book:author'' и  добавили этот префикс к атрибуту ''title'' элемента ''book:author''.
+
In the above example we circumvent the last rule by adding a ''title'' attribute from the ''http://trolltech.com/fnord/'' namespace to ''book:author'': the ''fnord:title'' comes from the namespace with the prefix ''fnord'' that is declared in the ''book:author'' element.
-
Очевидно, пространство имен ''fnord'' имеет точно такое же URI, что и пространство имен по умолчанию. Почему же мы просто не использовали ранее объявленное пространство имен по умолчанию? Ответ не совсем простой:
+
Clearly the ''fnord'' namespace has the same namespace URI as the default namespace. So why didn't we simply use the default namespace we'd already declared? The answer is quite complex:
-
*атрибуты без префикса вообще не принадлежат никакому пространству имен, даже пространству имен по умолчанию;
+
*attributes without a prefix don't belong to any XML namespace at all, not even to the default namespace;
-
*пренебрежение префиксом будет приводить к конфликту типа ''title-title'';
+
*additionally omitting the prefix would lead to a ''title-title'' clash;
-
*запись префикса как ''xmlns:title'' позволит объявить новое пространство имен с префиксом ''title'' вместо используемого пространства имен по умолчанию ''xmlns''.
+
*writing it as ''xmlns:title'' would declare a new namespace with the prefix ''title'' instead of applying the default ''xmlns'' namespace.
-
Используя классы Qt XML доступ к элементам и атрибутам может осуществляться двумя способами: либо ссылаясь на их квалифицированные имена, включающие префикс пространства имен и "реальное" имя (или "локальное" имя), либо используя комбинацию локального имени и URI пространства имен.  
+
With the Qt XML classes elements and attributes can be accessed in two ways: either by refering to their qualified names consisting of the namespace prefix and the "real" name (or ''local'' name) or by the combination of local name and namespace URI.
-
Дополнительную информацию о пространстве имен XML можно найти на [http://www.w3.org/TR/REC-xml-names/ http://www.w3.org/TR/REC-xml-names/].
+
More information on XML namespaces can be found at [http://www.w3.org/TR/REC-xml-names/ http://www.w3.org/TR/REC-xml-names/].
-
<div id="namespacesconventions"></div><div id="conventions-used-in-the-qt-xml-documentation"></div>
+
-
====Conventions Used in the Qt XML Documentation====
+
-
Следующие термины используются для различия частей имен в контексте пространства имен:
+
====Conventions Used in the Qt XML Documentation====
 +
The following terms are used to distinguish the parts of names within the context of namespaces:
-
*''квалифицированное имя'' (''qualified name'') - это имя как оно представляется в документе. (В примерах, представленных выше, ''book:title'' это квалифицированное имя.)
+
*The ''qualified name'' is the name as it appears in the document. (In the above example ''book:title'' is a qualified name.)
-
*''префикс пространства имен'' (''namespace prefix'') - часть квалифицированного имени слева от ":". (''book'' - это префикс пространства имен в ''book:title''.)
+
*A ''namespace prefix'' in a qualified name is the part to the left of the ":". (''book'' is the namespace prefix in ''book:title''.)
-
*''локальная часть'' (''local part'') - часть квалифицированного имени справа от ":" (иногда ее называют ''локальное имя'' (''local name'')). (''title'' - локальная часть часть ''book:title''.)
+
*The ''local part'' of a name (also refered to as the ''local name'') appears to the right of the ":". (Thus ''title'' is the local part of ''book:title''.)
-
*''пространство имен URI'' (''namespace URI'' ("Uniform Resource Identifier")) - это уникальный идентификатор пространства имен. Внешне он выглядит подобно URL (например, ''http://trolltech.com/fnord/'' ), но не требует, чтобы по этому адресу были доступны какие-либо данные.
+
*The ''namespace URI'' ("Uniform Resource Identifier") is a unique identifier for a namespace. It looks like a URL (e.g&#x2e; ''http://trolltech.com/fnord/'' ) but does not require data to be accessible by the given protocol at the named address.
-
Элементы без ":" (в примере подобно ''chapter'') не имеют префикса пространства имен. В этом случае локальная часть и квалифицированное имя идентичны (например, ''chapter'').
+
Elements without a ":" (like ''chapter'' in the example) do not have a namespace prefix. In this case the local part and the qualified name are identical (i.e&#x2e; ''chapter'').
-
Также смотрите [[Qt:Документация 4.3.2/xml-dombookmarks | DOM Bookmarks Example]] и [[Qt:Документация 4.3.2/xml-saxbookmarks | SAX Bookmarks Example]].
+
See also [[Qt:Документация 4.3.2/xml-dombookmarks | DOM Bookmarks Example]] and [[Qt:Документация 4.3.2/xml-saxbookmarks | SAX Bookmarks Example]].
-
[Previous: [[Qt:Документация 4.3.2/qtsvg | QtSvg Module]] ] [ [[Qt:Документация 4.3.2/modules | Qt's Modules]] ] [Next: [[Qt:Документация 4.3.2/qtdesigner | QtDesigner Module]] ]  
+
[Previous: [[Qt:Документация 4.3.2/qtsvg | QtSvg Module]]] [ [[Qt:Документация 4.3.2/modules | Qt's Modules]] ] [Next: [[Qt:Документация 4.3.2/qtdesigner | QtDesigner Module]]]
{{Qt4.3.2_footer}}
{{Qt4.3.2_footer}}

Пожалуйста, обратите внимание, что все ваши добавления могут быть отредактированы или удалены другими участниками. Если вы не хотите, чтобы кто-либо изменял ваши тексты, не помещайте их сюда.
Вы также подтверждаете, что являетесь автором вносимых дополнений, или скопировали их из источника, допускающего свободное распространение и изменение своего содержимого (см. Wiki.crossplatform.ru:Авторское право). НЕ РАЗМЕЩАЙТЕ БЕЗ РАЗРЕШЕНИЯ ОХРАНЯЕМЫЕ АВТОРСКИМ ПРАВОМ МАТЕРИАЛЫ!


Шаблоны, использованные на текущей версии страницы: