Major plugin refactor and cleanup.

Switched to POCO library for unified platform/library interface.
Deprecated the external module API. It was creating more problems than solving.
Removed most built-in libraries in favor of system libraries for easier maintenance.
Cleaned and secured code with help from static analyzers.
This commit is contained in:
Sandu Liviu Catalin committed 2021-01-30 08:51:39 +02:00
1 parent e0e34b4030
commit 4a6bfc086c
6219 files changed
+1209835 -454916

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
//
// Content.h
//
// Library: XML
// Package: XML
// Module: Content
//
// Definition of the Content enum.
//
// Copyright (c) 2015, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Based on libstudxml (http://www.codesynthesis.com/projects/libstudxml/).
// Copyright (c) 2009-2013 Code Synthesis Tools CC.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_Content_INCLUDED
#define XML_Content_INCLUDED
namespace Poco {
namespace XML {
struct Content
/// XML content model. C++11 enum class emulated for C++98.
///
/// element characters whitespaces notes
/// Empty no no ignored
/// Simple no yes preserved content accumulated
/// Complex yes no ignored
/// Mixed yes yes preserved
{
enum value
{
Empty,
Simple,
Complex,
Mixed
};
Content(value v)
: _v(v)
{
}
operator value() const
{
return _v;
}
private:
value _v;
};
} } // namespace Poco::XML
#endif // XML_Content_INCLUDED
+144
View File
@@ -0,0 +1,144 @@
//
// Name.h
//
// Library: XML
// Package: XML
// Module: Name
//
// Definition of the Name class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_Name_INCLUDED
#define XML_Name_INCLUDED
#include "Poco/XML/XML.h"
#include "Poco/XML/XMLString.h"
namespace Poco {
namespace XML {
class XML_API Name
/// An XML element or attribute name, consisting of a
/// qualified name, a namespace URI and a local name.
{
public:
Name();
/// Creates an empty Name.
Name(const XMLString& qname);
/// Creates a Name from a qualified name only.
Name(const XMLString& qname, const XMLString& namespaceURI);
/// Creates a Name from a qualified name and a namespace URI.
/// The local name is extracted from the qualified name.
Name(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName);
/// Creates a Name from a qualified name, a namespace URI and a local name.
Name(const Name& name);
/// Copy constructor.
Name(Name&& name) noexcept;
/// Move constructor.
~Name();
/// Destroys the name.
Name& operator = (const Name& name);
/// Assignment operator.
Name& operator = (Name&& name) noexcept;
/// Move assignment.
void swap(Name& name);
/// Swaps the name with another one.
void assign(const XMLString& qname);
/// Assigns a new value to the name.
void assign(const XMLString& qname, const XMLString& namespaceURI);
/// Assigns new values to the name.
/// The local name is extracted from the qualified name.
void assign(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName);
/// Assigns new values to the name.
bool equals(const Name& name) const;
/// Returns true if both names are equal.
bool equals(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName) const;
/// Returns true if all the name's components are equal to the given ones.
bool equalsWeakly(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName) const;
/// Returns true if either the qnames are identical or the namespaceURIs and the localNames are identical.
const XMLString& qname() const;
/// Returns the qualified name.
const XMLString& namespaceURI() const;
/// Returns the namespace URI.
const XMLString& localName() const;
/// Returns the local name.
XMLString prefix() const;
/// Returns the namespace prefix.
static void split(const XMLString& qname, XMLString& prefix, XMLString& localName);
/// Splits the given qualified name into its prefix and localName parts.
static XMLString localName(const XMLString& qname);
/// Returns the local name part of the given qualified name.
static XMLString prefix(const XMLString& qname);
/// Returns the prefix part of the given qualified name.
static const XMLString EMPTY_NAME;
private:
XMLString _qname;
XMLString _namespaceURI;
XMLString _localName;
};
//
// inlines
//
inline const XMLString& Name::qname() const
{
return _qname;
}
inline const XMLString& Name::namespaceURI() const
{
return _namespaceURI;
}
inline const XMLString& Name::localName() const
{
return _localName;
}
inline void swap(Name& n1, Name& n2)
{
n1.swap(n2);
}
} } // namespace Poco::XML
#endif // XML_Name_INCLUDED
+83
View File
@@ -0,0 +1,83 @@
//
// NamePool.h
//
// Library: XML
// Package: XML
// Module: NamePool
//
// Definition of the NamePool class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_NamePool_INCLUDED
#define XML_NamePool_INCLUDED
#include "Poco/XML/XML.h"
#include "Poco/XML/XMLString.h"
#include "Poco/XML/Name.h"
#ifndef POCO_XML_NAMEPOOL_DEFAULT_SIZE
#define POCO_XML_NAMEPOOL_DEFAULT_SIZE 509
#endif
namespace Poco {
namespace XML {
class NamePoolItem;
class XML_API NamePool
/// A hashtable that stores XML names consisting of an URI, a
/// local name and a qualified name.
{
public:
NamePool(unsigned long size = POCO_XML_NAMEPOOL_DEFAULT_SIZE);
/// Creates a name pool with room for up to size strings.
///
/// The given size should be a suitable prime number,
/// e.g. 251, 509, 1021 or 4093.
const Name& insert(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName);
/// Returns a const reference to an Name for the given names.
/// Creates the Name if it does not already exist.
/// Throws a PoolOverflowException if the name pool is full.
const Name& insert(const Name& name);
/// Returns a const reference to an Name for the given name.
/// Creates the Name if it does not already exist.
/// Throws a PoolOverflowException if the name pool is full.
void duplicate();
/// Increments the reference count.
void release();
/// Decrements the reference count and deletes the object if the reference count reaches zero.
protected:
unsigned long hash(const XMLString& qname, const XMLString& namespaceURI, const XMLString& localName);
~NamePool();
private:
NamePool(const NamePool&);
NamePool& operator = (const NamePool&);
NamePoolItem* _pItems;
unsigned long _size;
unsigned long _salt;
int _rc;
};
} } // namespace Poco::XML
#endif // XML_NamePool_INCLUDED
+115
View File
@@ -0,0 +1,115 @@
//
// NamespaceStrategy.h
//
// Library: XML
// Package: XML
// Module: NamespaceStrategy
//
// Definition of the NamespaceStrategy class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_NamespaceStrategy_INCLUDED
#define XML_NamespaceStrategy_INCLUDED
#include "Poco/XML/XML.h"
#include "Poco/XML/XMLString.h"
#include "Poco/SAX/NamespaceSupport.h"
#include "Poco/SAX/AttributesImpl.h"
namespace Poco {
namespace XML {
class ContentHandler;
class XML_API NamespaceStrategy
/// This class is used by ParserEngine to handle the
/// startElement, endElement, startPrefixMapping and
/// endPrefixMapping events.
{
public:
virtual ~NamespaceStrategy();
virtual void startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler) = 0;
/// Translate the arguments as delivered by Expat and
/// call the startElement() method of the ContentHandler.
virtual void endElement(const XMLChar* name, ContentHandler* pContentHandler) = 0;
/// Translate the arguments as delivered by Expat and
/// call the endElement() method of the ContentHandler.
protected:
static void splitName(const XMLChar* qname, XMLString& uri, XMLString& localName);
static void splitName(const XMLChar* qname, XMLString& uri, XMLString& localName, XMLString& prefix);
static const XMLString NOTHING;
};
class XML_API NoNamespacesStrategy: public NamespaceStrategy
/// The NamespaceStrategy implementation used if no namespaces
/// processing is requested.
{
public:
NoNamespacesStrategy();
~NoNamespacesStrategy();
void startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler);
void endElement(const XMLChar* name, ContentHandler* pContentHandler);
private:
XMLString _name;
AttributesImpl _attrs;
};
class XML_API NoNamespacePrefixesStrategy: public NamespaceStrategy
/// The NamespaceStrategy implementation used if namespaces
/// processing is requested, but prefixes are not reported.
{
public:
NoNamespacePrefixesStrategy();
~NoNamespacePrefixesStrategy();
void startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler);
void endElement(const XMLChar* name, ContentHandler* pContentHandler);
private:
XMLString _uri;
XMLString _local;
AttributesImpl _attrs;
};
class XML_API NamespacePrefixesStrategy: public NamespaceStrategy
/// The NamespaceStrategy implementation used if namespaces
/// processing is requested and prefixes are reported.
{
public:
NamespacePrefixesStrategy();
~NamespacePrefixesStrategy();
void startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler);
void endElement(const XMLChar* name, ContentHandler* pContentHandler);
private:
XMLString _uri;
XMLString _local;
XMLString _qname;
AttributesImpl _attrs;
};
} } // namespace Poco::XML
#endif // XML_NamespaceStrategy_INCLUDED
+358
View File
@@ -0,0 +1,358 @@
//
// ParserEngine.h
//
// Library: XML
// Package: XML
// Module: ParserEngine
//
// Definition of the ParseEngine class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
#ifndef XML_ParserEngine_INCLUDED
#define XML_ParserEngine_INCLUDED
#include "Poco/XML/XML.h"
#if defined(POCO_UNBUNDLED)
#include <expat.h>
#else
#include "Poco/XML/expat.h"
#endif
#include "Poco/XML/XMLString.h"
#include "Poco/XML/XMLStream.h"
#include "Poco/SAX/Locator.h"
#include "Poco/TextEncoding.h"
#include <map>
#include <vector>
namespace Poco {
namespace XML {
class InputSource;
class EntityResolver;
class DTDHandler;
class DeclHandler;
class ContentHandler;
class LexicalHandler;
class ErrorHandler;
class NamespaceStrategy;
class ContextLocator;
class XML_API ParserEngine: public Locator
/// This class provides an object-oriented, stream-based,
/// low-level interface to the XML Parser Toolkit (expat).
/// It is strongly recommended, that you use the
/// SAX parser classes (which are based on this
/// class) instead of this class, since they provide
/// a standardized, higher-level interface to the parser.
{
public:
ParserEngine();
/// Creates the parser engine.
ParserEngine(const XMLString& encoding);
/// Creates the parser engine and passes the encoding
/// to the underlying parser.
~ParserEngine();
/// Destroys the parser.
void setEncoding(const XMLString& encoding);
/// Sets the encoding used by expat. The encoding must be
/// set before parsing begins, otherwise it will be ignored.
const XMLString& getEncoding() const;
/// Returns the encoding used by expat.
void addEncoding(const XMLString& name, Poco::TextEncoding* pEncoding);
/// Adds an encoding to the parser.
void setNamespaceStrategy(NamespaceStrategy* pStrategy);
/// Sets the NamespaceStrategy used by the parser.
/// The parser takes ownership of the strategy object
/// and deletes it when it's no longer needed.
/// The default is NoNamespacesStrategy.
NamespaceStrategy* getNamespaceStrategy() const;
/// Returns the NamespaceStrategy currently in use.
void setExpandInternalEntities(bool flag = true);
/// Enables/disables expansion of internal entities (enabled by
/// default). If entity expansion is disabled, internal entities
/// are reported via the default handler.
/// Must be set before parsing begins, otherwise it will be
/// ignored.
bool getExpandInternalEntities() const;
/// Returns true if internal entities will be expanded automatically,
/// which is the default.
void setExternalGeneralEntities(bool flag = true);
/// Enable or disable processing of external general entities.
bool getExternalGeneralEntities() const;
/// Returns true if external general entities will be processed; false otherwise.
void setExternalParameterEntities(bool flag = true);
/// Enable or disable processing of external parameter entities.
bool getExternalParameterEntities() const;
/// Returns true if external parameter entities will be processed; false otherwise.
void setEntityResolver(EntityResolver* pResolver);
/// Allow an application to register an entity resolver.
EntityResolver* getEntityResolver() const;
/// Return the current entity resolver.
void setDTDHandler(DTDHandler* pDTDHandler);
/// Allow an application to register a DTD event handler.
DTDHandler* getDTDHandler() const;
/// Return the current DTD handler.
void setDeclHandler(DeclHandler* pDeclHandler);
/// Allow an application to register a DTD declarations event handler.
DeclHandler* getDeclHandler() const;
/// Return the current DTD declarations handler.
void setContentHandler(ContentHandler* pContentHandler);
/// Allow an application to register a content event handler.
ContentHandler* getContentHandler() const;
/// Return the current content handler.
void setLexicalHandler(LexicalHandler* pLexicalHandler);
/// Allow an application to register a lexical event handler.
LexicalHandler* getLexicalHandler() const;
/// Return the current lexical handler.
void setErrorHandler(ErrorHandler* pErrorHandler);
/// Allow an application to register an error event handler.
ErrorHandler* getErrorHandler() const;
/// Return the current error handler.
void setEnablePartialReads(bool flag = true);
/// Enable or disable partial reads from the input source.
///
/// This is useful for parsing XML from a socket stream for
/// a protocol like XMPP, where basically single elements
/// are read one at a time from the input source's stream, and
/// following elements depend upon responses sent back to
/// the peer.
///
/// Normally, the parser always reads blocks of PARSE_BUFFER_SIZE
/// at a time, and blocks until a complete block has been read (or
/// the end of the stream has been reached).
/// This allows for efficient parsing of "complete" XML documents,
/// but fails in a case such as XMPP, where only XML fragments
/// are sent at a time.
bool getEnablePartialReads() const;
/// Returns true if partial reads are enabled (see
/// setEnablePartialReads()), false otherwise.
void parse(InputSource* pInputSource);
/// Parse an XML document from the given InputSource.
void parse(const char* pBuffer, std::size_t size);
/// Parses an XML document from the given buffer.
// Locator
XMLString getPublicId() const;
/// Return the public identifier for the current document event.
XMLString getSystemId() const;
/// Return the system identifier for the current document event.
int getLineNumber() const;
/// Return the line number where the current document event ends.
int getColumnNumber() const;
/// Return the column number where the current document event ends.
protected:
void init();
/// initializes expat
void parseByteInputStream(XMLByteInputStream& istr);
/// Parses an entity from the given stream.
void parseCharInputStream(XMLCharInputStream& istr);
/// Parses an entity from the given stream.
std::streamsize readBytes(XMLByteInputStream& istr, char* pBuffer, std::streamsize bufferSize);
/// Reads at most bufferSize bytes from the given stream into the given buffer.
std::streamsize readChars(XMLCharInputStream& istr, XMLChar* pBuffer, std::streamsize bufferSize);
/// Reads at most bufferSize chars from the given stream into the given buffer.
void handleError(int errorNo);
/// Throws an XMLException with a message corresponding
/// to the given Expat error code.
void parseExternal(XML_Parser extParser, InputSource* pInputSource);
/// Parse an XML document from the given InputSource.
void parseExternalByteInputStream(XML_Parser extParser, XMLByteInputStream& istr);
/// Parses an external entity from the given stream, with a separate parser.
void parseExternalCharInputStream(XML_Parser extParser, XMLCharInputStream& istr);
/// Parses an external entity from the given stream, with a separate parser.
void pushContext(XML_Parser parser, InputSource* pInputSource);
/// Pushes a new entry to the context stack.
void popContext();
/// Pops the top-most entry from the context stack.
void resetContext();
/// Resets and clears the context stack.
const Locator& locator() const;
/// Returns a locator denoting the current parse location.
// expat handler procedures
static void handleStartElement(void* userData, const XML_Char* name, const XML_Char** atts);
static void handleEndElement(void* userData, const XML_Char* name);
static void handleCharacterData(void* userData, const XML_Char* s, int len);
static void handleProcessingInstruction(void* userData, const XML_Char* target, const XML_Char* data);
static void handleDefault(void* userData, const XML_Char* s, int len);
static void handleUnparsedEntityDecl(void* userData, const XML_Char* entityName, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId, const XML_Char* notationName);
static void handleNotationDecl(void* userData, const XML_Char* notationName, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId);
static int handleExternalEntityRef(XML_Parser parser, const XML_Char* openEntityNames, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId);
static int handleUnknownEncoding(void* encodingHandlerData, const XML_Char* name, XML_Encoding* info);
static void handleComment(void* userData, const XML_Char* data);
static void handleStartCdataSection(void* userData);
static void handleEndCdataSection(void* userData);
static void handleStartNamespaceDecl(void* userData, const XML_Char* prefix, const XML_Char* uri);
static void handleEndNamespaceDecl(void* userData, const XML_Char* prefix);
static void handleStartDoctypeDecl(void* userData, const XML_Char* doctypeName, const XML_Char *systemId, const XML_Char* publicId, int hasInternalSubset);
static void handleEndDoctypeDecl(void* userData);
static void handleEntityDecl(void *userData, const XML_Char *entityName, int isParamEntity, const XML_Char *value, int valueLength,
const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName);
static void handleExternalParsedEntityDecl(void* userData, const XML_Char* entityName, const XML_Char* base, const XML_Char* systemId, const XML_Char* publicId);
static void handleInternalParsedEntityDecl(void* userData, const XML_Char* entityName, const XML_Char* replacementText, int replacementTextLength);
static void handleSkippedEntity(void* userData, const XML_Char* entityName, int isParameterEntity);
// encoding support
static int convert(void *data, const char *s);
private:
typedef std::map<XMLString, Poco::TextEncoding*> EncodingMap;
typedef std::vector<ContextLocator*> ContextStack;
XML_Parser _parser;
char* _pBuffer;
bool _encodingSpecified;
XMLString _encoding;
bool _expandInternalEntities;
bool _externalGeneralEntities;
bool _externalParameterEntities;
bool _enablePartialReads;
NamespaceStrategy* _pNamespaceStrategy;
EncodingMap _encodings;
ContextStack _context;
EntityResolver* _pEntityResolver;
DTDHandler* _pDTDHandler;
DeclHandler* _pDeclHandler;
ContentHandler* _pContentHandler;
LexicalHandler* _pLexicalHandler;
ErrorHandler* _pErrorHandler;
static const int PARSE_BUFFER_SIZE;
static const XMLString EMPTY_STRING;
};
//
// inlines
//
inline const XMLString& ParserEngine::getEncoding() const
{
return _encoding;
}
inline NamespaceStrategy* ParserEngine::getNamespaceStrategy() const
{
return _pNamespaceStrategy;
}
inline bool ParserEngine::getExpandInternalEntities() const
{
return _expandInternalEntities;
}
inline bool ParserEngine::getExternalGeneralEntities() const
{
return _externalGeneralEntities;
}
inline bool ParserEngine::getExternalParameterEntities() const
{
return _externalParameterEntities;
}
inline EntityResolver* ParserEngine::getEntityResolver() const
{
return _pEntityResolver;
}
inline DTDHandler* ParserEngine::getDTDHandler() const
{
return _pDTDHandler;
}
inline DeclHandler* ParserEngine::getDeclHandler() const
{
return _pDeclHandler;
}
inline ContentHandler* ParserEngine::getContentHandler() const
{
return _pContentHandler;
}
inline LexicalHandler* ParserEngine::getLexicalHandler() const
{
return _pLexicalHandler;
}
inline ErrorHandler* ParserEngine::getErrorHandler() const
{
return _pErrorHandler;
}
inline bool ParserEngine::getEnablePartialReads() const
{
return _enablePartialReads;
}
} } // namespace Poco::XML
#endif // XML_ParserEngine_INCLUDED
+148
View File
@@ -0,0 +1,148 @@
//
// QName.h
//
// Library: XML
// Package: XML
// Module: QName
//
// Definition of the QName class.
//
// Copyright (c) 2015, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Based on libstudxml (http://www.codesynthesis.com/projects/libstudxml/).
// Copyright (c) 2009-2013 Code Synthesis Tools CC.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_QName_INCLUDED
#define XML_QName_INCLUDED
#include "Poco/XML/XML.h"
#include <string>
#include <iosfwd>
namespace Poco {
namespace XML {
class XML_API QName
/// This class represents a qualified XML name in the stream parser.
///
/// Note that the optional prefix is just a "syntactic sugar". In
/// particular, it is ignored by the comparison operators and the
/// std::ostream insertion operator.
{
public:
QName();
QName(const std::string& name);
QName(const std::string& ns, const std::string& name);
QName(const std::string& ns, const std::string& name, const std::string& prefix);
QName(const QName& qname);
QName(QName&& qname) noexcept;
QName& operator = (const QName& qname);
QName& operator = (QName&& qname) noexcept;
void swap(QName& qname);
const std::string& namespaceURI() const;
/// Returns the namespace URI part of the name.
const std::string& localName() const;
/// Returns the local part of the name.
const std::string& prefix() const;
/// Returns the namespace prefix of the name.
std::string& namespaceURI();
/// Returns the namespace URI part of the name.
std::string& localName();
/// Returns the local part of the name.
std::string& prefix();
/// Returns the namespace prefix of the name.
std::string toString() const;
/// Returns a printable representation in the [<namespace>#]<name> form.
public:
friend bool operator < (const QName& x, const QName& y);
friend bool operator == (const QName& x, const QName& y);
friend bool operator != (const QName& x, const QName& y);
private:
std::string _ns;
std::string _name;
std::string _prefix;
};
//
// inlines
//
inline const std::string& QName::namespaceURI() const
{
return _ns;
}
inline const std::string& QName::localName() const
{
return _name;
}
inline const std::string& QName::prefix() const
{
return _prefix;
}
inline std::string& QName::namespaceURI()
{
return _ns;
}
inline std::string& QName::localName()
{
return _name;
}
inline std::string& QName::prefix()
{
return _prefix;
}
XML_API std::ostream& operator << (std::ostream&, const QName&);
inline bool operator < (const QName& x, const QName& y)
{
return x._ns < y._ns || (x._ns == y._ns && x._name < y._name);
}
inline bool operator == (const QName& x, const QName& y)
{
return x._ns == y._ns && x._name == y._name;
}
inline bool operator != (const QName& x, const QName& y)
{
return !(x == y);
}
} } // namespace Poco::XML
#endif // XML_QName_INCLUDED
+104
View File
@@ -0,0 +1,104 @@
//
// ValueTraits.h
//
// Library: XML
// Package: XML
// Module: ValueTraits
//
// Definition of the ValueTraits templates.
//
// Copyright (c) 2015, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Based on libstudxml (http://www.codesynthesis.com/projects/libstudxml/).
// Copyright (c) 2009-2013 Code Synthesis Tools CC.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_ValueTraits_INCLUDED
#define XML_ValueTraits_INCLUDED
#include "XMLStreamParserException.h"
#include <string>
#include <cstddef>
#include <iostream>
#include <sstream>
namespace Poco {
namespace XML {
class XMLStreamParser;
class XMLStreamSerializer;
template <typename T>
struct DefaultValueTraits
{
static T
parse(std::string, const XMLStreamParser&);
static std::string
serialize(const T&, const XMLStreamSerializer&);
};
template <>
struct XML_API DefaultValueTraits<bool>
{
static bool
parse(std::string, const XMLStreamParser&);
static std::string serialize(bool v, const XMLStreamSerializer&)
{
return v ? "true" : "false";
}
};
template <>
struct XML_API DefaultValueTraits<std::string>
{
static std::string parse(std::string s, const XMLStreamParser&)
{
return s;
}
static std::string serialize(const std::string& v, const XMLStreamSerializer&)
{
return v;
}
};
template <typename T>
struct ValueTraits: DefaultValueTraits<T>
{
};
template <typename T, std::size_t N>
struct ValueTraits<T[N]> : DefaultValueTraits<const T*>
{
};
template <typename T>
T DefaultValueTraits<T>::parse(std::string s, const XMLStreamParser& p)
{
T r;
std::istringstream is(s);
if (!(is >> r && is.eof()))
throw XMLStreamParserException(p, "invalid value '" + s + "'");
return r;
}
} } // namespace Poco::XML
#endif // XML_ValueTraits_INCLUDED
+62
View File
@@ -0,0 +1,62 @@
//
// XML.h
//
// Library: XML
// Package: XML
// Module: XML
//
// Basic definitions for the Poco XML library.
// This file must be the first file included by every other XML
// header file.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_XML_INCLUDED
#define XML_XML_INCLUDED
#include "Poco/Foundation.h"
//
// The following block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the XML_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// XML_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
//
#if defined(_WIN32) && defined(POCO_DLL)
#if defined(XML_EXPORTS)
#define XML_API __declspec(dllexport)
#else
#define XML_API __declspec(dllimport)
#endif
#endif
#if !defined(XML_API)
#if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4)
#define XML_API __attribute__ ((visibility ("default")))
#else
#define XML_API
#endif
#endif
//
// Automatically link XML library.
//
#if defined(_MSC_VER)
#if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(XML_EXPORTS)
#pragma comment(lib, "PocoXML" POCO_LIB_SUFFIX)
#endif
#endif
#endif // XML_XML_INCLUDED
+37
View File
@@ -0,0 +1,37 @@
//
// XMLException.h
//
// Library: XML
// Package: XML
// Module: XMLException
//
// Definition of the XMLException class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_XMLException_INCLUDED
#define XML_XMLException_INCLUDED
#include "Poco/XML/XML.h"
#include "Poco/Exception.h"
namespace Poco {
namespace XML {
POCO_DECLARE_EXCEPTION(XML_API, XMLException, Poco::RuntimeException)
/// The base class for all XML-related exceptions like SAXException
/// and DOMException.
} } // namespace Poco::XML
#endif // XML_XMLException_INCLUDED
+71
View File
@@ -0,0 +1,71 @@
//
// XMLStream.h
//
// Library: XML
// Package: XML
// Module: XMLStream
//
// Definition of the XMLByteInputStream and XMLCharInputStream classes.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_XMLStream_INCLUDED
#define XML_XMLStream_INCLUDED
#include "Poco/XML/XML.h"
#include <istream>
#include <ostream>
namespace Poco {
namespace XML {
// The byte input stream is always a narrow stream.
using XMLByteInputStream = std::istream;
using XMLByteOutputStream = std::ostream;
//
// The XML parser uses the stream classes provided by the C++
// standard library (based on the basic_stream<> template).
// In Unicode mode, a wide stream is used.
// To turn on Unicode mode, #define XML_UNICODE and
// XML_UNICODE_WCHAR_T when compiling the library.
//
// XML_UNICODE XML_UNICODE_WCHAR_T XMLCharInputStream XMLCharOutputStream
// -------------------------------------------------------------------------
// N N std::istream std::ostream
// N Y std::wistream std::wostream
// Y Y std::wistream std::wostream
// Y N <not supported>
//
#if defined(XML_UNICODE_WCHAR_T)
// Unicode - use wide streams
using XMLCharInputStream = std::wistream;
using XMLCharOutputStream = std::wostream;
#elif defined(XML_UNICODE)
// not supported - leave XMLString undefined
#else
// Characters are UTF-8 encoded
using XMLCharInputStream = std::istream;
using XMLCharOutputStream = std::ostream;
#endif
} } // namespace Poco::XML
#endif // XML_XMLStream_INCLUDED
+634
View File
@@ -0,0 +1,634 @@
//
// XMLStreamParser.h
//
// Library: XML
// Package: XML
// Module: XMLStreamParser
//
// Definition of the XMLStreamParser class.
//
// Copyright (c) 2015, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Based on libstudxml (http://www.codesynthesis.com/projects/libstudxml/).
// Copyright (c) 2009-2013 Code Synthesis Tools CC.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_XMLStreamParser_INCLUDED
#define XML_XMLStreamParser_INCLUDED
// We only support UTF-8 expat.
#ifdef XML_UNICODE
#error UTF-16 expat (XML_UNICODE defined) is not supported
#endif
#include "Poco/XML/QName.h"
#include "Poco/XML/ValueTraits.h"
#include "Poco/XML/Content.h"
#if defined(POCO_UNBUNDLED)
#include <expat.h>
#else
#include "Poco/XML/expat.h"
#endif
#include <map>
#include <vector>
#include <string>
#include <iosfwd>
#include <cstddef>
namespace Poco {
namespace XML {
class XML_API XMLStreamParser
/// The streaming XML pull parser and streaming XML serializer. The parser
/// is a conforming, non-validating XML 1.0 implementation (see Implementation Notes
/// for details). The application character encoding (that is, the encoding used
/// in the application's memory) for both parser and serializer is UTF-8.
/// The output encoding of the serializer is UTF-8 as well. The parser supports
/// UTF-8, UTF-16, ISO-8859-1, and US-ASCII input encodings.
///
/// Attribute map:
///
/// Attribute map lookup. If attribute is not found, then the version
/// without the default value throws an appropriate parsing exception
/// while the version with the default value returns that value.
///
/// Note also that there is no attribute(ns, name) version since it
/// would conflict with attribute(name, dv) (qualified attributes
/// are not very common).
///
/// Attribute map is valid throughout at the "element level" until
/// end_element and not just during EV_START_ELEMENT. As a special case,
/// the map is still valid after peek() that returned end_element until
/// this end_element event is retrieved with next().
///
/// Using parser:
///
/// XMLStreamParser p(ifs, argv[1]);
/// for (XMLStreamParser::EventType e: p)
/// {
/// switch (e)
/// {
/// case XMLStreamParser::EV_START_ELEMENT:
/// cerr << p.line () << ':' << p.column () << ": start " << p.name () << endl;
/// break;
/// case XMLStreamParser::EV_END_ELEMENT:
/// cerr << p.line () << ':' << p.column () << ": end " << p.name () << endl;
/// break;
/// case XMLStreamParser::EV_START_ATTRIBUTE:
/// ...
/// case XMLStreamParser::EV_END_ATTRIBUTE:
/// ...
/// case XMLStreamParser::EV_CHARACTERS:
/// ...
/// }
/// }
{
public:
enum EventType
/// Parsing events.
{
EV_START_ELEMENT,
EV_END_ELEMENT,
EV_START_ATTRIBUTE,
EV_END_ATTRIBUTE,
EV_CHARACTERS,
EV_START_NAMESPACE_DECL,
EV_END_NAMESPACE_DECL,
EV_EOF
};
using FeatureType = unsigned short;
/// If both receive_attributes_event and RECEIVE_ATTRIBUTE_MAP are
/// specified, then RECEIVE_ATTRIBUTES_EVENT is assumed.
static const FeatureType RECEIVE_ELEMENTS = 0x0001;
static const FeatureType RECEIVE_CHARACTERS = 0x0002;
static const FeatureType RECEIVE_ATTRIBUTE_MAP = 0x0004;
static const FeatureType RECEIVE_ATTRIBUTES_EVENT = 0x0008;
static const FeatureType RECEIVE_NAMESPACE_DECLS = 0x0010;
static const FeatureType RECEIVE_DEFAULT = RECEIVE_ELEMENTS | RECEIVE_CHARACTERS | RECEIVE_ATTRIBUTE_MAP;
struct AttributeValueType
{
std::string value;
mutable bool handled;
};
using AttributeMapType = std::map<QName, AttributeValueType>;
struct XML_API Iterator
// C++11 range-based for support. Generally, the iterator interface
// doesn't make much sense for the XMLStreamParser so for now we have an
// implementation that is just enough to the range-based for.
{
using value_type = EventType;
Iterator(XMLStreamParser* p = 0, EventType e = EV_EOF):
_parser(p),
_e(e)
{
}
value_type operator * () const
{
return _e;
}
Iterator& operator ++ ()
{
_e = _parser->next();
return *this;
}
bool operator == (Iterator y) const
/// Comparison only makes sense when comparing to end (eof).
{
return _e == EV_EOF && y._e == EV_EOF;
}
bool operator != (Iterator y) const
/// Comparison only makes sense when comparing to end (eof).
{
return !(*this == y);
}
private:
XMLStreamParser* _parser;
EventType _e;
};
Iterator begin()
{
return Iterator(this, next());
}
Iterator end()
{
return Iterator(this, EV_EOF);
}
XMLStreamParser(std::istream&, const std::string& inputName, FeatureType = RECEIVE_DEFAULT);
/// The parser constructor takes three arguments: the stream to parse,
/// input name that is used in diagnostics to identify the document being
/// parsed, and the list of events we want the parser to report.
///
/// Parse std::istream. Input name is used in diagnostics to identify
/// the document being parsed.
///
/// If stream exceptions are enabled then std::ios_base::failure
/// exception is used to report io errors (badbit and failbit).
/// Otherwise, those are reported as the parsing exception.
XMLStreamParser(const void* data, std::size_t size, const std::string& inputName, FeatureType = RECEIVE_DEFAULT);
/// Parse memory buffer that contains the whole document. Input name
/// is used in diagnostics to identify the document being parsed.
~XMLStreamParser();
/// Destroys the XMLStreamParser.
EventType next();
/// Call the next() function when we are ready to handle the next piece of XML.
void nextExpect(EventType);
/// Get the next event and make sure that it's what's expected. If it
/// is not, then throw an appropriate parsing exception.
void nextExpect(EventType, const std::string& name);
void nextExpect(EventType, const QName& qname);
void nextExpect(EventType, const std::string& ns, const std::string& name);
EventType peek();
EventType event();
/// Return the event that was last returned by the call to next() or peek().
const std::string& inputName() const;
const QName& getQName() const;
const std::string& namespaceURI() const;
const std::string& localName() const;
const std::string& prefix() const;
std::string& value();
const std::string& value() const;
template <typename T> T value() const;
Poco::UInt64 line() const;
Poco::UInt64 column() const;
const std::string& attribute(const std::string& name) const;
template <typename T>
T attribute(const std::string& name) const;
std::string attribute(const std::string& name, const std::string& deflt) const;
template <typename T>
T attribute(const std::string& name, const T& deflt) const;
const std::string& attribute(const QName& qname) const;
template <typename T>
T attribute(const QName& qname) const;
std::string attribute(const QName& qname, const std::string& deflt) const;
template <typename T>
T attribute(const QName& qname, const T& deflt) const;
bool attributePresent(const std::string& name) const;
bool attributePresent(const QName& qname) const;
const AttributeMapType& attributeMap() const;
void content(Content);
Content content() const;
void nextExpect(EventType, const std::string& name, Content);
void nextExpect(EventType, const QName& qname, Content);
void nextExpect(EventType, const std::string& ns, const std::string& name, Content);
// Helpers for parsing elements with simple content. The first two
// functions assume that EV_START_ELEMENT has already been parsed. The
// rest parse the complete element, from start to end.
//
// Note also that as with attribute(), there is no (namespace,name)
// overload since it would conflicts with (namespace,deflt).
std::string element();
template <typename T>
T element();
std::string element(const std::string& name);
std::string element(const QName& qname);
template <typename T>
T element(const std::string& name);
template <typename T>
T element(const QName& qname);
std::string element(const std::string& name, const std::string& deflt);
std::string element(const QName& qname, const std::string& deflt);
template <typename T>
T element(const std::string& name, const T& deflt);
template <typename T>
T element(const QName& qname, const T& deflt);
private:
XMLStreamParser(const XMLStreamParser&);
XMLStreamParser& operator = (const XMLStreamParser&);
static void XMLCALL handleStartElement(void*, const XML_Char*, const XML_Char**);
static void XMLCALL handleEndElement(void*, const XML_Char*);
static void XMLCALL handleCharacters(void*, const XML_Char*, int);
static void XMLCALL handleStartNamespaceDecl(void*, const XML_Char*, const XML_Char*);
static void XMLCALL handleEndNamespaceDecl(void*, const XML_Char*);
void init();
EventType nextImpl(bool peek);
EventType nextBody();
void handleError();
// If _size is 0, then data is std::istream. Otherwise, it is a buffer.
union
{
std::istream* is;
const void* buf;
}
_data;
std::size_t _size;
const std::string _inputName;
FeatureType _feature;
XML_Parser _parser;
std::size_t _depth;
bool _accumulateContent; // Whether we are accumulating character content.
enum { state_next, state_peek } _parserState;
EventType _currentEvent;
EventType _queue;
QName _qname;
std::string _value;
const QName* _qualifiedName;
std::string* _pvalue;
Poco::UInt64 _line;
Poco::UInt64 _column;
struct AttributeType
{
QName qname;
std::string value;
};
typedef std::vector<AttributeType> attributes;
attributes _attributes;
attributes::size_type _currentAttributeIndex; // Index of the current attribute.
typedef std::vector<QName> NamespaceDecls;
NamespaceDecls _startNamespace;
NamespaceDecls::size_type _startNamespaceIndex;// Index of the current decl.
NamespaceDecls _endNamespace;
NamespaceDecls::size_type _endNamespaceIndex;// Index of the current decl.
struct ElementEntry
{
ElementEntry(std::size_t d, Content c = Content::Mixed):
depth(d),
content(c),
attributesUnhandled(0)
{
}
std::size_t depth;
Content content;
AttributeMapType attributeMap;
mutable AttributeMapType::size_type attributesUnhandled;
};
typedef std::vector<ElementEntry> ElementState;
std::vector<ElementEntry> _elementState;
const AttributeMapType _emptyAttrMap;
const ElementEntry* getElement() const;
const ElementEntry* getElementImpl() const;
void popElement();
};
XML_API std::ostream& operator << (std::ostream&, XMLStreamParser::EventType);
//
// inlines
//
inline XMLStreamParser::EventType XMLStreamParser::event()
// Return the even that was last returned by the call to next() or peek().
{
return _currentEvent;
}
inline const std::string& XMLStreamParser::inputName() const
{
return _inputName;
}
inline const QName& XMLStreamParser::getQName() const
{
return *_qualifiedName;
}
inline const std::string& XMLStreamParser::namespaceURI() const
{
return _qualifiedName->namespaceURI();
}
inline const std::string& XMLStreamParser::localName() const
{
return _qualifiedName->localName();
}
inline const std::string& XMLStreamParser::prefix() const
{
return _qualifiedName->prefix();
}
inline std::string& XMLStreamParser::value()
{
return *_pvalue;
}
inline const std::string& XMLStreamParser::value() const
{
return *_pvalue;
}
inline Poco::UInt64 XMLStreamParser::line() const
{
return _line;
}
inline Poco::UInt64 XMLStreamParser::column() const
{
return _column;
}
inline XMLStreamParser::EventType XMLStreamParser::peek()
{
if (_parserState == state_peek)
return _currentEvent;
else
{
EventType e(nextImpl(true));
_parserState = state_peek; // Set it after the call to nextImpl().
return e;
}
}
template <typename T>
inline T XMLStreamParser::value() const
{
return ValueTraits < T > ::parse(value(), *this);
}
inline const std::string& XMLStreamParser::attribute(const std::string& n) const
{
return attribute(QName(n));
}
template <typename T>
inline T XMLStreamParser::attribute(const std::string& n) const
{
return attribute < T > (QName(n));
}
inline std::string XMLStreamParser::attribute(const std::string& n, const std::string& dv) const
{
return attribute(QName(n), dv);
}
template <typename T>
inline T XMLStreamParser::attribute(const std::string& n, const T& dv) const
{
return attribute < T > (QName(n), dv);
}
template <typename T>
inline T XMLStreamParser::attribute(const QName& qn) const
{
return ValueTraits < T > ::parse(attribute(qn), *this);
}
inline bool XMLStreamParser::attributePresent(const std::string& n) const
{
return attributePresent(QName(n));
}
inline const XMLStreamParser::AttributeMapType& XMLStreamParser::attributeMap() const
{
if (const ElementEntry* e = getElement())
{
e->attributesUnhandled = 0; // Assume all handled.
return e->attributeMap;
}
return _emptyAttrMap;
}
inline void XMLStreamParser::nextExpect(EventType e, const QName& qn)
{
nextExpect(e, qn.namespaceURI(), qn.localName());
}
inline void XMLStreamParser::nextExpect(EventType e, const std::string& n)
{
nextExpect(e, std::string(), n);
}
inline void XMLStreamParser::nextExpect(EventType e, const QName& qn, Content c)
{
nextExpect(e, qn);
poco_assert(e == EV_START_ELEMENT);
content(c);
}
inline void XMLStreamParser::nextExpect(EventType e, const std::string& n, Content c)
{
nextExpect(e, std::string(), n);
poco_assert(e == EV_START_ELEMENT);
content(c);
}
inline void XMLStreamParser::nextExpect(EventType e, const std::string& ns, const std::string& n, Content c)
{
nextExpect(e, ns, n);
poco_assert(e == EV_START_ELEMENT);
content(c);
}
template <typename T>
inline T XMLStreamParser::element()
{
return ValueTraits < T > ::parse(element(), *this);
}
inline std::string XMLStreamParser::element(const std::string& n)
{
nextExpect(EV_START_ELEMENT, n);
return element();
}
inline std::string XMLStreamParser::element(const QName& qn)
{
nextExpect(EV_START_ELEMENT, qn);
return element();
}
template <typename T>
inline T XMLStreamParser::element(const std::string& n)
{
return ValueTraits < T > ::parse(element(n), *this);
}
template <typename T>
inline T XMLStreamParser::element(const QName& qn)
{
return ValueTraits < T > ::parse(element(qn), *this);
}
inline std::string XMLStreamParser::element(const std::string& n, const std::string& dv)
{
return element(QName(n), dv);
}
template <typename T>
inline T XMLStreamParser::element(const std::string& n, const T& dv)
{
return element < T > (QName(n), dv);
}
inline void XMLStreamParser::content(Content c)
{
poco_assert(_parserState == state_next);
if (!_elementState.empty() && _elementState.back().depth == _depth)
_elementState.back().content = c;
else
_elementState.emplace_back(_depth, c);
}
inline Content XMLStreamParser::content() const
{
poco_assert(_parserState == state_next);
return !_elementState.empty() && _elementState.back().depth == _depth ? _elementState.back().content : Content(Content::Mixed);
}
inline const XMLStreamParser::ElementEntry* XMLStreamParser::getElement() const
{
return _elementState.empty() ? 0 : getElementImpl();
}
template <typename T>
T XMLStreamParser::attribute(const QName& qn, const T& dv) const
{
if (const ElementEntry* e = getElement())
{
AttributeMapType::const_iterator i(e->attributeMap.find(qn));
if (i != e->attributeMap.end())
{
if (!i->second.handled)
{
i->second.handled = true;
e->attributesUnhandled--;
}
return ValueTraits < T > ::parse(i->second.value, *this);
}
}
return dv;
}
template <typename T>
T XMLStreamParser::element(const QName& qn, const T& dv)
{
if (peek() == EV_START_ELEMENT && getQName() == qn)
{
next();
return element<T>();
}
return dv;
}
} } // namespace Poco::XML
#endif // XML_XMLStreamParser_INCLUDED
@@ -0,0 +1,58 @@
//
// XMLStreamParserException.h
//
// Library: XML
// Package: XML
// Module: XMLStreamParserException
//
// Definition of the XMLStreamParserException class.
//
// Copyright (c) 2015, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_XMLStreamParserException_INCLUDED
#define XML_XMLStreamParserException_INCLUDED
#include "Poco/XML/XMLException.h"
namespace Poco {
namespace XML {
class XMLStreamParser;
class XML_API XMLStreamParserException: public Poco::XML::XMLException
{
public:
XMLStreamParserException(const std::string& name, Poco::UInt64 line, Poco::UInt64 column, const std::string& description);
XMLStreamParserException(const XMLStreamParser&, const std::string& description);
virtual ~XMLStreamParserException() throw ();
const char* name() const noexcept;
Poco::UInt64 line() const;
Poco::UInt64 column() const;
const std::string& description() const;
virtual const char* what() const throw ();
private:
void init();
std::string _name;
Poco::UInt64 _line;
Poco::UInt64 _column;
std::string _description;
std::string _what;
};
} } // namespace Poco::XML
#endif // XML_XMLStreamParserException_INCLUDED
+87
View File
@@ -0,0 +1,87 @@
//
// XMLString.h
//
// Library: XML
// Package: XML
// Module: XMLString
//
// Definition of the XMLString class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_XMLString_INCLUDED
#define XML_XMLString_INCLUDED
#include "Poco/XML/XML.h"
namespace Poco {
namespace XML {
//
// The XML parser uses the string classes provided by the C++
// standard library (based on the basic_string<> template).
// In Unicode mode, a std::wstring is used, otherwise
// a std::string is used.
// To turn on Unicode mode, #define XML_UNICODE and
// XML_UNICODE_WCHAR_T when compiling the library.
//
// XML_UNICODE XML_UNICODE_WCHAR_T XMLChar XMLString
// --------------------------------------------------------------
// N N char std::string
// N Y wchar_t std::wstring
// Y Y wchar_t std::wstring
// Y N <not supported>
//
#if defined(XML_UNICODE_WCHAR_T)
// Unicode - use wchar_t
using XMLChar = wchar_t;
using XMLString = std::wstring;
std::string fromXMLString(const XMLString& str);
/// Converts an XMLString into an UTF-8 encoded
/// string.
XMLString toXMLString(const std::string& str);
/// Converts an UTF-8 encoded string into an
/// XMLString
#define XML_LIT(lit) L##lit
#elif defined(XML_UNICODE)
// not supported - leave XMLString undefined
#else
// Characters are UTF-8 encoded
using XMLChar = char;
using XMLString = std::string;
inline const std::string& fromXMLString(const XMLString& str)
{
return str;
}
inline const XMLString& toXMLString(const std::string& str)
{
return str;
}
#define XML_LIT(lit) lit
#endif
} } // namespace Poco::XML
#endif // XML_XMLString_INCLUDED
+375
View File
@@ -0,0 +1,375 @@
//
// XMLWriter.h
//
// Library: XML
// Package: XML
// Module: XMLWriter
//
// Definition of the XMLWriter class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef XML_XMLWriter_INCLUDED
#define XML_XMLWriter_INCLUDED
#include "Poco/XML/XML.h"
#include "Poco/SAX/ContentHandler.h"
#include "Poco/SAX/LexicalHandler.h"
#include "Poco/SAX/DTDHandler.h"
#include "Poco/SAX/NamespaceSupport.h"
#include "Poco/XML/XMLString.h"
#include "Poco/XML/XMLStream.h"
#include "Poco/XML/Name.h"
#include "Poco/TextEncoding.h"
#include "Poco/StreamConverter.h"
#include <vector>
#include <map>
namespace Poco {
namespace XML {
class Locator;
class XML_API XMLWriter: public ContentHandler, public LexicalHandler, public DTDHandler
/// This class serializes SAX2 ContentHandler, LexicalHandler and
/// DTDHandler events back into a stream.
///
/// Various consistency checks are performed on the written data
/// (i.e. there must be exactly one root element and every startElement()
/// must have a matching endElement()).
///
/// The XMLWriter supports optional pretty-printing of the serialized XML.
/// Note, however, that pretty-printing XML data alters the
/// information set of the document being written, since in
/// XML all whitespace is potentially relevant to an application.
///
/// The writer contains extensive support for XML Namespaces, so that a client
/// application does not have to keep track of prefixes and supply xmlns attributes.
///
/// If the client does not provide namespace prefixes (either by specifying them
/// as part of the qualified name given to startElement(), or by calling
/// startPrefixMapping()), the XMLWriter automatically generates namespace
/// prefixes in the form ns1, ns2, etc.
{
public:
enum Options
{
CANONICAL = 0x00,
/// Do not write an XML declaration (default).
CANONICAL_XML = 0x01,
/// Enables basic support for Canonical XML:
/// - do not write an XML declaration
/// - do not use special empty element syntax
/// - set the New Line character to NEWLINE_LF
/// - write namespace declarations and attributes
/// in canonical order
/// - use default namespace as much as possible
WRITE_XML_DECLARATION = 0x02,
/// Write an XML declaration.
PRETTY_PRINT = 0x04,
/// Pretty-print XML markup.
PRETTY_PRINT_ATTRIBUTES = 0x08
/// Write each attribute on a separate line.
/// PRETTY_PRINT must be specified as well.
};
XMLWriter(XMLByteOutputStream& str, int options);
/// Creates the XMLWriter and sets the specified options.
///
/// The resulting stream will be UTF-8 encoded.
XMLWriter(XMLByteOutputStream& str, int options, const std::string& encodingName, Poco::TextEncoding& textEncoding);
/// Creates the XMLWriter and sets the specified options.
///
/// The encoding is reflected in the XML declaration.
/// The caller is responsible for that the given encodingName matches with
/// the given textEncoding.
XMLWriter(XMLByteOutputStream& str, int options, const std::string& encodingName, Poco::TextEncoding* pTextEncoding);
/// Creates the XMLWriter and sets the specified options.
///
/// The encoding is reflected in the XML declaration.
/// The caller is responsible for that the given encodingName matches with
/// the given textEncoding.
/// If pTextEncoding is null, the given encodingName is ignored and the
/// default UTF-8 encoding is used.
~XMLWriter();
/// Destroys the XMLWriter.
void setNewLine(const std::string& newLineCharacters);
/// Sets the line ending for the resulting XML file.
///
/// Possible values are:
/// * NEWLINE_DEFAULT (whatever is appropriate for the current platform)
/// * NEWLINE_CRLF (Windows),
/// * NEWLINE_LF (Unix),
/// * NEWLINE_CR (Macintosh)
const std::string& getNewLine() const;
/// Returns the line ending currently in use.
void setIndent(const std::string& indent);
/// Sets the string used for one indentation step.
///
/// The default is a single TAB character.
/// The given string should only contain TAB or SPACE
/// characters (e.g., a single TAB character, or
/// two to four SPACE characters).
const std::string& getIndent() const;
/// Returns the string used for one indentation step.
// ContentHandler
void setDocumentLocator(const Locator* loc);
/// Currently unused.
void startDocument();
/// Writes a generic XML declaration to the stream.
/// If a document type has been set (see SetDocumentType),
/// a DOCTYPE declaration is also written.
void endDocument();
/// Checks that all elements are closed and prints a final newline.
void startFragment();
/// Use this instead of StartDocument() if you want to write
/// a fragment rather than a document (no XML declaration and
/// more than one "root" element allowed).
void endFragment();
/// Checks that all elements are closed and prints a final newline.
void startElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes);
/// Writes an XML start element tag.
///
/// Namespaces are handled as follows.
/// 1. If a qname, but no namespaceURI and localName are given, the qname is taken as element name.
/// 2. If a namespaceURI and a localName, but no qname is given, and the given namespaceURI has been
/// declared earlier, the namespace prefix for the given namespaceURI together with the localName
/// is taken as element name. If the namespace has not been declared, a prefix in the form
/// "ns1", "ns2", etc. is generated and the namespace is declared with the generated prefix.
/// 3. If all three are given, and the namespace given in namespaceURI has not been declared, it is declared now.
/// Otherwise, see 2.
void startElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname);
/// Writes an XML start element tag with no attributes.
/// See the other startElement() method for more information.
void endElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname);
/// Writes an XML end element tag.
///
/// Throws an exception if the name of doesn't match the
/// one of the most recent startElement().
void emptyElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname);
/// Writes an empty XML element tag (<elem/>).
void emptyElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes);
/// Writes an empty XML element tag with the given attributes (<elem attr1="value1"... />).
void characters(const XMLChar ch[], int start, int length);
/// Writes XML character data. Quotes, ampersand's, less-than and
/// greater-than signs are escaped, unless a CDATA section
/// has been opened by calling startCDATA().
///
/// The characters must be encoded in UTF-8 (if XMLChar is char) or
/// UTF-16 (if XMLChar is wchar_t).
void characters(const XMLString& str);
/// Writes XML character data. Quotes, ampersand's, less-than and
/// greater-than signs are escaped, unless a CDATA section
/// has been opened by calling startCDATA().
///
/// The characters must be encoded in UTF-8 (if XMLChar is char) or
/// UTF-16 (if XMLChar is wchar_t).
void rawCharacters(const XMLString& str);
/// Writes the characters in the given string as they are.
/// The caller is responsible for escaping characters as
/// necessary to produce valid XML.
///
/// The characters must be encoded in UTF-8 (if XMLChar is char) or
/// UTF-16 (if XMLChar is wchar_t).
void ignorableWhitespace(const XMLChar ch[], int start, int length);
/// Writes whitespace characters by simply passing them to
/// characters().
void processingInstruction(const XMLString& target, const XMLString& data);
/// Writes a processing instruction.
void startPrefixMapping(const XMLString& prefix, const XMLString& namespaceURI);
/// Begin the scope of a prefix-URI Namespace mapping.
/// A namespace declaration is written with the next element.
void endPrefixMapping(const XMLString& prefix);
/// End the scope of a prefix-URI mapping.
void skippedEntity(const XMLString& name);
/// Does nothing.
void dataElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const XMLString& data,
const XMLString& attr1 = XMLString(), const XMLString& value1 = XMLString(),
const XMLString& attr2 = XMLString(), const XMLString& value2 = XMLString(),
const XMLString& attr3 = XMLString(), const XMLString& value3 = XMLString());
/// Writes a data element in the form <name attr1="value1"...>data</name>.
// LexicalHandler
void startCDATA();
/// Writes the <![CDATA[ string that begins a CDATA section.
/// Use characters() to write the actual character data.
void endCDATA();
/// Writes the ]]> string that ends a CDATA section.
void comment(const XMLChar ch[], int start, int length);
/// Writes a comment.
void startDTD(const XMLString& name, const XMLString& publicId, const XMLString& systemId);
/// Writes a DTD declaration.
void endDTD();
/// Writes the closing characters of a DTD declaration.
void startEntity(const XMLString& name);
/// Does nothing.
void endEntity(const XMLString& name);
/// Does nothing.
// DTDHandler
void notationDecl(const XMLString& name, const XMLString* publicId, const XMLString* systemId);
void unparsedEntityDecl(const XMLString& name, const XMLString* publicId, const XMLString& systemId, const XMLString& notationName);
static const std::string NEWLINE_DEFAULT;
static const std::string NEWLINE_CR;
static const std::string NEWLINE_CRLF;
static const std::string NEWLINE_LF;
// Namespace support.
XMLString uniquePrefix();
/// Creates and returns a unique namespace prefix that
/// can be used with startPrefixMapping().
bool isNamespaceMapped(const XMLString& namespc) const;
/// Returns true if the given namespace has been mapped
/// to a prefix in the current element or its ancestors.
// Misc.
int depth() const;
/// Return the number of nested XML elements.
///
/// Will be -1 if no document or fragment has been started,
/// 0 if the document or fragment has been started,
/// 1 if the document element has been written and
/// > 1 for every element nested within the document element.
protected:
typedef std::map<XMLString, XMLString> AttributeMap;
typedef std::map<XMLString, std::pair<XMLString, XMLString>> CanonicalAttributeMap;
void writeStartElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes);
void writeCanonicalStartElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes);
void writeEndElement(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname);
void writeMarkup(const std::string& str) const;
void writeXML(const XMLString& str) const;
void writeXML(XMLChar ch) const;
void writeNewLine() const;
void writeIndent() const;
void writeIndent(int indent) const;
void writeName(const XMLString& prefix, const XMLString& localName);
void writeXMLDeclaration();
void closeStartTag();
void declareNamespaces(const XMLString& namespaceURI, const XMLString& localName, const XMLString& qname, const Attributes& attributes);
void declareAttributeNamespaces(const Attributes& attributes);
void addNamespaceAttributes(AttributeMap& attributeMap);
void addNamespaceAttributes(CanonicalAttributeMap& attributeMap);
void addAttributes(AttributeMap& attributeMap, const Attributes& attributes, const XMLString& elementNamespaceURI);
void addAttributes(CanonicalAttributeMap& attributeMap, const Attributes& attributes, const XMLString& elementNamespaceURI);
void writeAttributes(const AttributeMap& attributeMap);
void writeAttributes(const CanonicalAttributeMap& attributeMap);
void prettyPrint() const;
static std::string nameToString(const XMLString& localName, const XMLString& qname);
private:
struct Namespace
{
Namespace(const XMLString& thePrefix, const XMLString& theNamespaceURI):
prefix(thePrefix),
namespaceURI(theNamespaceURI)
{
}
XMLString prefix;
XMLString namespaceURI;
};
typedef std::vector<Name> ElementStack;
Poco::OutputStreamConverter* _pTextConverter;
Poco::TextEncoding* _pInEncoding;
Poco::TextEncoding* _pOutEncoding;
int _options;
std::string _encoding;
std::string _newLine;
int _depth;
int _elementCount;
bool _inFragment;
bool _inCDATA;
bool _inDTD;
bool _inInternalDTD;
bool _contentWritten;
bool _unclosedStartTag;
ElementStack _elementStack;
NamespaceSupport _namespaces;
int _prefix;
bool _nsContextPushed;
std::string _indent;
static const std::string MARKUP_QUOTENC;
static const std::string MARKUP_AMPENC;
static const std::string MARKUP_LTENC;
static const std::string MARKUP_GTENC;
static const std::string MARKUP_TABENC;
static const std::string MARKUP_CRENC;
static const std::string MARKUP_LFENC;
static const std::string MARKUP_LT;
static const std::string MARKUP_GT;
static const std::string MARKUP_SLASHGT;
static const std::string MARKUP_LTSLASH;
static const std::string MARKUP_COLON;
static const std::string MARKUP_EQQUOT;
static const std::string MARKUP_QUOT;
static const std::string MARKUP_SPACE;
static const std::string MARKUP_TAB;
static const std::string MARKUP_BEGIN_CDATA;
static const std::string MARKUP_END_CDATA;
};
//
// inlines
//
inline int XMLWriter::depth() const
{
return _depth;
}
} } // namespace Poco::XML
#endif // XML_XMLWriter_INCLUDED
File diff suppressed because it is too large. Load diff
+158
View File
@@ -0,0 +1,158 @@
/*
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000-2017 Expat development team
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef Expat_External_INCLUDED
#define Expat_External_INCLUDED 1
/* External API definitions */
/* Expat tries very hard to make the API boundary very specifically
defined. There are two macros defined to control this boundary;
each of these can be defined before including this header to
achieve some different behavior, but doing so it not recommended or
tested frequently.
XMLCALL - The calling convention to use for all calls across the
"library boundary." This will default to cdecl, and
try really hard to tell the compiler that's what we
want.
XMLIMPORT - Whatever magic is needed to note that a function is
to be imported from a dynamically loaded library
(.dll, .so, or .sl, depending on your platform).
The XMLCALL macro was added in Expat 1.95.7. The only one which is
expected to be directly useful in client code is XMLCALL.
Note that on at least some Unix versions, the Expat library must be
compiled with the cdecl calling convention as the default since
system headers may assume the cdecl convention.
*/
#ifndef XMLCALL
# if defined(_MSC_VER)
# define XMLCALL __cdecl
# elif defined(__GNUC__) && defined(__i386) && ! defined(__INTEL_COMPILER)
# define XMLCALL __attribute__((cdecl))
# else
/* For any platform which uses this definition and supports more than
one calling convention, we need to extend this definition to
declare the convention used on that platform, if it's possible to
do so.
If this is the case for your platform, please file a bug report
with information on how to identify your platform via the C
pre-processor and how to specify the same calling convention as the
platform's malloc() implementation.
*/
# define XMLCALL
# endif
#endif /* not defined XMLCALL */
#if ! defined(XML_STATIC) && ! defined(XMLIMPORT)
# ifndef XML_BUILDING_EXPAT
/* using Expat from an application */
# if defined(_MSC_EXTENSIONS) && ! defined(__BEOS__) && ! defined(__CYGWIN__)
# define XMLIMPORT __declspec(dllimport)
# endif
# endif
#endif /* not defined XML_STATIC */
#ifndef XML_ENABLE_VISIBILITY
# define XML_ENABLE_VISIBILITY 0
#endif
#if ! defined(XMLIMPORT) && XML_ENABLE_VISIBILITY
# define XMLIMPORT __attribute__((visibility("default")))
#endif
/* If we didn't define it above, define it away: */
#ifndef XMLIMPORT
# define XMLIMPORT
#endif
#if defined(__GNUC__) \
&& (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96))
# define XML_ATTR_MALLOC __attribute__((__malloc__))
#else
# define XML_ATTR_MALLOC
#endif
#if defined(__GNUC__) \
&& ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
# define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x)))
#else
# define XML_ATTR_ALLOC_SIZE(x)
#endif
#define XMLPARSEAPI(type) XMLIMPORT type XMLCALL
#ifdef __cplusplus
extern "C" {
#endif
#ifdef XML_UNICODE_WCHAR_T
# ifndef XML_UNICODE
# define XML_UNICODE
# endif
# if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2)
# error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc"
# endif
#endif
#ifdef XML_UNICODE /* Information is UTF-16 encoded. */
# ifdef XML_UNICODE_WCHAR_T
typedef wchar_t XML_Char;
typedef wchar_t XML_LChar;
# else
typedef unsigned short XML_Char;
typedef char XML_LChar;
# endif /* XML_UNICODE_WCHAR_T */
#else /* Information is UTF-8 encoded. */
typedef char XML_Char;
typedef char XML_LChar;
#endif /* XML_UNICODE */
#ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */
typedef long long XML_Index;
typedef unsigned long long XML_Size;
#else
typedef long XML_Index;
typedef unsigned long XML_Size;
#endif /* XML_LARGE_SIZE */
#ifdef __cplusplus
}
#endif
#endif /* not Expat_External_INCLUDED */