Tinyxml как раньше называли
Перейти к содержимому

Tinyxml как раньше называли

  • автор:

 

Русские Блоги

«Когда XML (расширенный язык тегов) был введен в индустрию программного обеспечения в феврале 1998 года, он принес шторм для всей отрасли. Впервые в истории этот мир имеет структурированный документ и данные. Универсальный формат и адаптивность, он Может не только использоваться для Интернета, но и может использоваться где угодно ».

XML относится к языку расширения, который является стандартом для обмена информацией.

Что такое tinyxml?

В настоящее время использование XML очень обширно. Чтение и настройка файлов конфигурации XML является нашими наиболее часто используемыми операциями. Обычные анализаторы C/C ++ XML включают Tinyxml, Xercess, Squashxml, Xmlite, Pugxml, Libxml и т. Д. Некоторые из этих анализаторов поддерживают мульти -языку, некоторые из них являются только C/C ++.

В настоящее время TinyXML является очень популярным анализатором XML на основе модели DOM. Он прост и прост в использовании, малый и изысканный. Он очень подходит для хранения простых данных, файлов конфигурации, сериализации объектов и других данных. Модель этой библиотеки анализа анализирует файл XML, а затем генерирует модель DOM в памяти, чтобы мы могли легко пройти это дерево XML.

Скачать и установить tinyxml

Установить: После разложения tinyxml добавьте эти шесть файлов в свой проект C ++, а именно TinyStr.h, tinyStr.cpp, tinyxml.h, tinyxml.cpp, tinyxmler.cpp, tinyxmlparser.cpp. Там, где вам необходимо управлять файлом XML, вы можете использовать следующий код, чтобы представить библиотеку TinyXML.

Tinyyxml Структура

Tixmlbase: базовый класс всей модели Tinyyxml.

Tixmlattribute: соответствует атрибутам элементов в XML.

Tixmlnode: узлы, соответствующие структуре DOM.

Tixmlcomment: примечания, соответствующие XML

TixmldeClaration: утверждение, соответствующее XML, то есть <? Версияг = "1.0"?>.

What it does.

In brief, TinyXML-2 parses an XML document, and builds from that a Document Object Model (DOM) that can be read, modified, and saved.

XML stands for «eXtensible Markup Language.» It is a general purpose human and machine readable markup language to describe arbitrary data. All those random file formats created to store application data can all be replaced with XML. One parser for everything.

There are different ways to access and interact with XML data. TinyXML-2 uses a Document Object Model (DOM), meaning the XML data is parsed into a C++ objects that can be browsed and manipulated, and then written to disk or another output stream. You can also construct an XML document from scratch with C++ objects and write this to disk or another output stream. You can even use TinyXML-2 to stream XML programmatically from code without creating a document first.

TinyXML-2 is designed to be easy and fast to learn. It is one header and one cpp file. Simply add these to your project and off you go. There is an example file — xmltest.cpp — to get you started.

TinyXML-2 is released under the ZLib license, so you can use it in open source or commercial code. The details of the license are at the top of every source file.

TinyXML-2 attempts to be a flexible parser, but with truly correct and compliant XML output. TinyXML-2 should compile on any reasonably C++ compliant system. It does not rely on exceptions, RTTI, or the STL.

What it doesn’t do.

TinyXML-2 doesn’t parse or use DTDs (Document Type Definitions) or XSLs (eXtensible Stylesheet Language.) There are other parsers out there that are much more fully featured. But they are generally bigger and more difficult to use. If you are working with browsers or have more complete XML needs, TinyXML-2 is not the parser for you.

TinyXML-1 vs. TinyXML-2

TinyXML-2 long been the focus of all development. It is well tested and should be used instead of TinyXML-1.

TinyXML-2 uses a similar API to TinyXML-1 and the same rich test cases. But the implementation of the parser is completely re-written to make it more appropriate for use in a game. It uses less memory, is faster, and uses far fewer memory allocations.

TinyXML-2 has no requirement or support for STL.

Features

Code Page

TinyXML-2 uses UTF-8 exclusively when interpreting XML. All XML is assumed to be UTF-8.

Filenames for loading / saving are passed unchanged to the underlying OS.

Memory Model

An XMLDocument is a C++ object like any other, that can be on the stack, or new’d and deleted on the heap.

However, any sub-node of the Document, XMLElement, XMLText, etc, can only be created by calling the appropriate XMLDocument::NewElement, NewText, etc. method. Although you have pointers to these objects, they are still owned by the Document. When the Document is deleted, so are all the nodes it contains.

White Space

Whitespace Preservation (default)

By default, TinyXML-2 preserves white space in a (hopefully) sane way that is almost compliant with the spec. (TinyXML-1 used a completely different model, much more similar to ‘collapse’, below.)

As a first step, all newlines / carriage-returns / line-feeds are normalized to a line-feed character, as required by the XML spec.

White space in text is preserved. For example:

The leading space before the «Hello» and the double space after the comma are preserved. Line-feeds are preserved, as in this example:

However, white space between elements is not preserved. Although not strictly compliant, tracking and reporting inter-element space is awkward, and not normally valuable. TinyXML-2 sees these as the same XML:

Whitespace Collapse

For some applications, it is preferable to collapse whitespace. Collapsing whitespace gives you «HTML-like» behavior, which is sometimes more suitable for hand typed documents.

TinyXML-2 supports this with the ‘whitespace’ parameter to the XMLDocument constructor. (The default is to preserve whitespace, as described above.)

However, you may also use COLLAPSE_WHITESPACE, which will:

  • Remove leading and trailing whitespace
  • Convert newlines and line-feeds into a space character
  • Collapse a run of any number of space characters into a single space character

Note that (currently) there is a performance impact for using COLLAPSE_WHITESPACE. It essentially causes the XML to be parsed twice.

Error Reporting

TinyXML-2 reports the line number of any errors in an XML document that cannot be parsed correctly. In addition, all nodes (elements, declarations, text, comments etc.) and attributes have a line number recorded as they are parsed. This allows an application that performs additional validation of the parsed XML document (e.g. application-implemented DTD validation) to report line number information for error messages.

Entities

TinyXML-2 recognizes the pre-defined «character entities», meaning special characters. Namely:

These are recognized when the XML document is read, and translated to their UTF-8 equivalents. For instance, text with the XML of:

will have the Value() of «Far & Away» when queried from the XMLText object, and will be written back to the XML stream/file as an ampersand.

Additionally, any character can be specified by its Unicode code point: The syntax &#xA0; or &#160; are both to the non-breaking space character. This is called a ‘numeric character reference’. Any numeric character reference that isn’t one of the special entities above, will be read, but written as a regular code point. The output is correct, but the entity syntax isn’t preserved.

Printing

Print to file

You can directly use the convenience function:

Or the XMLPrinter class:

Print to memory

Printing to memory is supported by the XMLPrinter.

Print without an XMLDocument

When loading, an XML parser is very useful. However, sometimes when saving, it just gets in the way. The code is often set up for streaming, and constructing the DOM is just overhead.

The Printer supports the streaming case. The following code prints out a trivially simple XML file without ever creating an XML document.

Examples

Load and parse an XML file.

Lookup information.

Using and Installing

There are 2 files in TinyXML-2:

  • tinyxml2.cpp

And additionally a test file:

  • xmltest.cpp

Generally speaking, the intent is that you simply include the tinyxml2.cpp and tinyxml2.h files in your project and build with your other source code.

There is also a CMake build included. CMake is the general build for TinyXML-2. Additional build systems are costly to maintain, and tend to bit-rot.

A Visual Studio project is included, but that is largely for developer convenience, and is not intended to integrate well with other builds.

Building TinyXML-2 — Using vcpkg

You can download and install TinyXML-2 using the vcpkg dependency manager:

The TinyXML-2 port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Versioning

TinyXML-2 uses semantic versioning. http://semver.org/ Releases are now tagged in github.

Note that the major version will (probably) change fairly rapidly. API changes are fairly common.

License

TinyXML-2 is released under the zlib license:

This software is provided ‘as-is’, without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

Contributors

Thanks very much to everyone who sends suggestions, bugs, ideas, and encouragement. It all helps, and makes this project fun.

The original TinyXML-1 has many contributors, who all deserve thanks in shaping what is a very successful library. Extra thanks to Yves Berquin and Andrew Ellerton who were key contributors.

TinyXML-2 grew from that effort. Lee Thomason is the original author of TinyXML-2 (and TinyXML-1) but TinyXML-2 has been and is being improved by many contributors.

Tinyxml как раньше называли

Войти

Авторизуясь в LiveJournal с помощью стороннего сервиса вы принимаете условия Пользовательского соглашения LiveJournal

Шпаргалка по TinyXML

Минимальный набор
TinyXML содержит в себе:

  • tinyxml.h
  • tinyxml.cpp
  • tinystr.cpp
  • tinyxmlerror.cpp
  • tinyxmlparser.cpp

Алгоритм работы
проще некуда, попробуем распарсить следующий
кусочек XML документа:

Текст функции:

//Создаем объект
документа XML и передаем ему имя файла
из которого

//мы будем читать

//Читаем файл
и проверяем — прочитался ли.
В случае невозможности

//чтения или распарсивания
функция вернет ошибку

//Класс TiXmlElement
— это основной кирпичик, на которые разбит

//документ XML.
Функция FirstChildElement возвращает первый элемент
в списке

//имя
которого "Parent".

TiXmlElement *element = doc.FirstChildElement("Parent");

//Берем
первый елемент под
именем "Child"

element = element- >FirstChildElement("Child");

//Перебираем все
элементы с именем "Child"

//Переменные для
извлечения значений из документа

 

//Функция QueryValueAttribute
"достает" из документа значения
атрибутов

//Следует сказать,
что функция перегружена для сех основных
типов данных

//включая строки
из стандартной библиотеки

//Если функция
вернула код TIXML_SUCCESS, то параметр считался

if(element- >QueryValueAttribute("param", &param) ==
TIXML_SUCCESS &&

element- >QueryValueAttribute("value", &value) == TIXML_SUCCESS)

//Здесь мы производим действия над извлеченными
данными

//Выбираем следующий
элемент из списка. Если элемент не существует

//то на следующей
итерации мы выйдем из цикла

element = element- >NextSiblingElement("action");

Таким образом,
мы легко и непринужденно можем считать,
к примеру, настройки своей программы
или какие-то типизированные данные. В
XML файле вполне может храниться небольшая
база данных или файл сохранения для игрового
момента 😉

Библиотека TinyXML
предоставляет программисту очень удобный
способ работы с XML. Для примера возьмем
такой фрагмент XML-файла:

Теперь фрагмент кода на С++, который иллюстрирует
работу с TinyXML (предварительно подключив
заголовочный файл библиотеки директивой
"#include" и внеся строку "tinyxml.lib"
в конфигурацию линковщика).

TiXmlDocument *xml_file = new TiXmlDocument("путь_к_файлу");

Следует учесть, что файл должен быть валидным,
т. е. не содержать ошибок. Например все
теги должны быть правильным образом закрыты
(< body / > или < body >< /body >) и так далее.

После открытия файла мы находимся в его
корне, поэтому элемент < level > будет являться
первым дочерним элементом всего файла.
Доступ к нему мы можем получить так:

TiXmlElement *xml_level = 0;

xml_level = xml_file- >FirstChildElement("level");

Функция FirstChildElement(имя_элемента) возвращает
указатель на первый дочерний элемент
объекта xml_file. Элемент < level > имеет дочерний

элемент < entity >, поэтому доступ к нему
мы получим уже через xml_level:

TiXmlElement *xml_entity = 0;

xml_entity = xml_level- >FirstChildElement("entity");

Поскольку элементов < entity > у нас несколько,
мы можем циклически пройтись по ним используя
функцию NextSiblingElement(имя_элемента), которая
возвращает указатель на соседний с текущим

элемент XML-файла:

//выполняем различные действия

xml_entity = xml_entity- >NextSiblingElement("entity");

Теперь, когда мы знаем как пройтись по
всем элементам XML-файла остается только
один важный и нужный момент — атрибуты
элемента. Получить их значение (типа const
char *) можно так:

What it does.

In brief, TinyXML-2 parses an XML document, and builds from that a Document Object Model (DOM) that can be read, modified, and saved.

XML stands for «eXtensible Markup Language.» It is a general purpose human and machine readable markup language to describe arbitrary data. All those random file formats created to store application data can all be replaced with XML. One parser for everything.

There are different ways to access and interact with XML data. TinyXML-2 uses a Document Object Model (DOM), meaning the XML data is parsed into a C++ objects that can be browsed and manipulated, and then written to disk or another output stream. You can also construct an XML document from scratch with C++ objects and write this to disk or another output stream. You can even use TinyXML-2 to stream XML programmatically from code without creating a document first.

TinyXML-2 is designed to be easy and fast to learn. It is one header and one cpp file. Simply add these to your project and off you go. There is an example file — xmltest.cpp — to get you started.

TinyXML-2 is released under the ZLib license, so you can use it in open source or commercial code. The details of the license are at the top of every source file.

TinyXML-2 attempts to be a flexible parser, but with truly correct and compliant XML output. TinyXML-2 should compile on any reasonably C++ compliant system. It does not rely on exceptions, RTTI, or the STL.

What it doesn’t do.

TinyXML-2 doesn’t parse or use DTDs (Document Type Definitions) or XSLs (eXtensible Stylesheet Language.) There are other parsers out there that are much more fully featured. But they are generally bigger and more difficult to use. If you are working with browsers or have more complete XML needs, TinyXML-2 is not the parser for you.

TinyXML-1 vs. TinyXML-2

TinyXML-2 long been the focus of all development. It is well tested and should be used instead of TinyXML-1.

TinyXML-2 uses a similar API to TinyXML-1 and the same rich test cases. But the implementation of the parser is completely re-written to make it more appropriate for use in a game. It uses less memory, is faster, and uses far fewer memory allocations.

TinyXML-2 has no requirement or support for STL.

Features

Code Page

TinyXML-2 uses UTF-8 exclusively when interpreting XML. All XML is assumed to be UTF-8.

Filenames for loading / saving are passed unchanged to the underlying OS.

Memory Model

An XMLDocument is a C++ object like any other, that can be on the stack, or new’d and deleted on the heap.

However, any sub-node of the Document, XMLElement, XMLText, etc, can only be created by calling the appropriate XMLDocument::NewElement, NewText, etc. method. Although you have pointers to these objects, they are still owned by the Document. When the Document is deleted, so are all the nodes it contains.

White Space

Whitespace Preservation (default)

By default, TinyXML-2 preserves white space in a (hopefully) sane way that is almost compliant with the spec. (TinyXML-1 used a completely different model, much more similar to ‘collapse’, below.)

As a first step, all newlines / carriage-returns / line-feeds are normalized to a line-feed character, as required by the XML spec.

White space in text is preserved. For example:

The leading space before the «Hello» and the double space after the comma are preserved. Line-feeds are preserved, as in this example:

However, white space between elements is not preserved. Although not strictly compliant, tracking and reporting inter-element space is awkward, and not normally valuable. TinyXML-2 sees these as the same XML:

Whitespace Collapse

For some applications, it is preferable to collapse whitespace. Collapsing whitespace gives you «HTML-like» behavior, which is sometimes more suitable for hand typed documents.

TinyXML-2 supports this with the ‘whitespace’ parameter to the XMLDocument constructor. (The default is to preserve whitespace, as described above.)

However, you may also use COLLAPSE_WHITESPACE, which will:

  • Remove leading and trailing whitespace
  • Convert newlines and line-feeds into a space character
  • Collapse a run of any number of space characters into a single space character

Note that (currently) there is a performance impact for using COLLAPSE_WHITESPACE. It essentially causes the XML to be parsed twice.

Error Reporting

TinyXML-2 reports the line number of any errors in an XML document that cannot be parsed correctly. In addition, all nodes (elements, declarations, text, comments etc.) and attributes have a line number recorded as they are parsed. This allows an application that performs additional validation of the parsed XML document (e.g. application-implemented DTD validation) to report line number information for error messages.

Entities

TinyXML-2 recognizes the pre-defined «character entities», meaning special characters. Namely:

These are recognized when the XML document is read, and translated to their UTF-8 equivalents. For instance, text with the XML of:

will have the Value() of «Far & Away» when queried from the XMLText object, and will be written back to the XML stream/file as an ampersand.

Additionally, any character can be specified by its Unicode code point: The syntax &#xA0; or &#160; are both to the non-breaking space character. This is called a ‘numeric character reference’. Any numeric character reference that isn’t one of the special entities above, will be read, but written as a regular code point. The output is correct, but the entity syntax isn’t preserved.

Printing

Print to file

You can directly use the convenience function:

Or the XMLPrinter class:

Print to memory

Printing to memory is supported by the XMLPrinter.

Print without an XMLDocument

When loading, an XML parser is very useful. However, sometimes when saving, it just gets in the way. The code is often set up for streaming, and constructing the DOM is just overhead.

The Printer supports the streaming case. The following code prints out a trivially simple XML file without ever creating an XML document.

Examples

Load and parse an XML file.

Lookup information.

Using and Installing

There are 2 files in TinyXML-2:

  • tinyxml2.cpp

And additionally a test file:

  • xmltest.cpp

Generally speaking, the intent is that you simply include the tinyxml2.cpp and tinyxml2.h files in your project and build with your other source code.

There is also a CMake build included. CMake is the general build for TinyXML-2. Additional build systems are costly to maintain, and tend to bit-rot.

A Visual Studio project is included, but that is largely for developer convenience, and is not intended to integrate well with other builds.

Building TinyXML-2 — Using vcpkg

You can download and install TinyXML-2 using the vcpkg dependency manager:

The TinyXML-2 port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Versioning

TinyXML-2 uses semantic versioning. http://semver.org/ Releases are now tagged in github.

Note that the major version will (probably) change fairly rapidly. API changes are fairly common.

License

TinyXML-2 is released under the zlib license:

This software is provided ‘as-is’, without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

Contributors

Thanks very much to everyone who sends suggestions, bugs, ideas, and encouragement. It all helps, and makes this project fun.

The original TinyXML-1 has many contributors, who all deserve thanks in shaping what is a very successful library. Extra thanks to Yves Berquin and Andrew Ellerton who were key contributors.

TinyXML-2 grew from that effort. Lee Thomason is the original author of TinyXML-2 (and TinyXML-1) but TinyXML-2 has been and is being improved by many contributors.

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *