// Мы встретили элемент 'ветеринар'.
animal.setVeterinarian(contactFromAttributes(attrs));
} else if (localname == trainer) {
// Мы встретили элемент 'дрессировщик'.
animal.setTrainer(contactFromAttributes(attrs));
} else {
// Мы встретили элемент 'кличка', 'вид животного' или
// 'дата рождения'. Их содержимое будет получено
// при обратном вызове функции characters().
currentText_.clear();
}
}
}
// Если текущий элемент представляет кличку, вид животного или дату
// рождения, используйте хранимый в currentText_ текст для установки
// соответствующего свойства текущего объекта Animal.
void endElement(
const XMLCh *const uri, // URI пространства имен
const XMLCh *const localname, // имя тега без префикса NS
const XMLCh *const qname) // имя тега + префикс NS
{
static XercesString animalList = fromNative('animal-list');
static XercesString animal = fromNative('animal');
static XercesString name = fromNative('name');
static XercesString species = fromNative('species');
static XercesString dob = fromNative('dateOfBirth');
if (localname!= animal && localname!= animalList) {
// currentText_ содержит текст элемента, который был
// добавлен. Используйте его для установки свойств текущего
// объекта Animal.
Animal& animal = animalList_.back();
if (localname == name) {
animal setName(toNative(currentText_));
} else if (localname == species) {
animal.setSpecies(toNative(currentText_));
} else if (localname == dob) {
animal.setDateOfBirth(toNative(currentText_));
}
}
}
// Получает уведомления, когда встречаются символьные данные
void characters(const XMLCh* const chars,
const unsigned int length) {
// Добавить символы в конец currentText_ для обработки методом
// endElement()
currentText_.append(chars, length);
}
private:
vector<Animal>& animalList_;
XercesString currentText_;
};
#include <stdexcept> // runtime_error
#include <xercesc/sax2/DefaultHandler.hpp>
// Получает уведомления об ошибках.
class CircusErrorHandler : public DefaultHandler {
public:
void warning(const SAXParseException& e) {
/* нет действий */
}
void error(const SAXParseExceptionf& e) {
throw runtime_error(toNative(e.getMessage()));
}
void fatalError(const SAXParseException& e) { error(e); }
};
#include <exception>
#include <iostream> // cout
#include <memory> // auto_ptr
#include <vector>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include 'animal.hpp'
#include 'xerces_strings.hpp' // Пример 14.4
using namespace std;
using namespace xercesc;
// Утилита RAII инициализирует парсер и освобождает ресурсы
// при выходе из области видимости
class XercesInitializer {
public:
XercesInitializer() { XMLPlatformUtils::Initialize(); }
~XercesInitializer() { XMLPlatformUtils::Terminate(); }
private:
// Запретить копирование и присваивание
XercesInitializer(const XercesInitializer&);
XercesInitializer& operator=(const XercesInitializer&);
};
int main() {
try {
vector<Animal> animalList;
// Инициализировать Xerces и получить парсер