Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qxmlstream.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
5#include "QtCore/qxmlstream.h"
6
7#if QT_CONFIG(xmlstream)
8
9#include "qxmlutils_p.h"
10
11#include <qdebug.h>
12#include <qfile.h>
13#include <stdio.h>
14#include <QtCore/qspan.h>
15#include <qstringconverter.h>
16#include <qstack.h>
17#include <qbuffer.h>
18#include <qscopeguard.h>
19#include <qcoreapplication.h>
20#include <QtCore/private/qduplicatetracker_p.h>
21#include <private/qoffsetstringarray_p.h>
22#include <private/qtools_p.h>
23
24#include <iterator>
25#include "qxmlstream_p.h"
26#include "qxmlstreamparser_p.h"
27#include <private/qstringconverter_p.h>
28#include <private/qstringiterator_p.h>
29
30#include <algorithm>
31
32QT_BEGIN_NAMESPACE
33
34using namespace QtPrivate;
35using namespace Qt::StringLiterals;
36using namespace QtMiscUtils;
37
38constexpr uint StreamEOF = ~0U;
39
40namespace {
41template <typename Range>
42auto reversed(Range &r)
43{
44 struct R {
45 Range *r;
46 auto begin() { return std::make_reverse_iterator(std::end(*r)); }
47 auto end() { return std::make_reverse_iterator(std::begin(*r)); }
48 };
49
50 return R{&r};
51}
52
53template <typename Range>
54void reversed(const Range &&) = delete;
55
56// implementation of missing QUtf8StringView methods for ASCII-only needles:
57auto transform(QLatin1StringView haystack, char needle)
58{
59 struct R { QLatin1StringView haystack; char16_t needle; };
60 return R{haystack, uchar(needle)};
61}
62
63auto transform(QStringView haystack, char needle)
64{
65 struct R { QStringView haystack; char16_t needle; };
66 return R{haystack, uchar(needle)};
67}
68
69auto transform(QUtf8StringView haystack, char needle)
70{
71 struct R { QByteArrayView haystack; char needle; };
72 return R{haystack, needle};
73}
74
75auto transform(QLatin1StringView haystack, QLatin1StringView needle)
76{
77 struct R { QLatin1StringView haystack; QLatin1StringView needle; };
78 return R{haystack, needle};
79}
80
81auto transform(QStringView haystack, QLatin1StringView needle)
82{
83 struct R { QStringView haystack; QLatin1StringView needle; };
84 return R{haystack, needle};
85}
86
87auto transform(QUtf8StringView haystack, QLatin1StringView needle)
88{
89 struct R { QLatin1StringView haystack; QLatin1StringView needle; };
90 return R{QLatin1StringView{QByteArrayView{haystack}}, needle};
91}
92
93#define WRAP(method, Needle)
94 auto method (QAnyStringView s, Needle needle) noexcept
95 {
96 return s.visit([needle](auto s) {
97 auto r = transform(s, needle);
98 return r.haystack. method (r.needle);
99 });
100 }
101 /*end*/
102
103WRAP(count, char)
104WRAP(contains, char)
105WRAP(contains, QLatin1StringView)
106WRAP(endsWith, char)
107WRAP(indexOf, QLatin1StringView)
108
109// ### begin move someplace central and complete
110template <auto V> struct Value { static constexpr auto value = V; };
111template <typename T> struct EncodingForHelper;
112template <> struct EncodingForHelper<QStringView> : Value<QStringDecoder::Utf16> {};
113template <> struct EncodingForHelper<QLatin1StringView> : Value<QStringDecoder::Latin1> {};
114template <bool B> struct EncodingForHelper<QBasicUtf8StringView<B>> : Value<QStringDecoder::Utf8> {};
115template <typename T>
116constexpr auto encodingFor = EncodingForHelper<T>::value;
117// ### end move someplace central
118
119} // unnamed namespace
120
121/*!
122 \enum QXmlStreamReader::TokenType
123
124 This enum specifies the type of token the reader just read.
125
126 \value NoToken The reader has not yet read anything.
127
128 \value Invalid An error has occurred, reported in error() and
129 errorString().
130
131 \value StartDocument The reader reports the XML version number in
132 documentVersion(), and the encoding as specified in the XML
133 document in documentEncoding(). If the document is declared
134 standalone, isStandaloneDocument() returns \c true; otherwise it
135 returns \c false.
136
137 \value EndDocument The reader reports the end of the document.
138
139 \value StartElement The reader reports the start of an element
140 with namespaceUri() and name(). Empty elements are also reported
141 as StartElement, followed directly by EndElement. The convenience
142 function readElementText() can be called to concatenate all
143 content until the corresponding EndElement. Attributes are
144 reported in attributes(), namespace declarations in
145 namespaceDeclarations().
146
147 \value EndElement The reader reports the end of an element with
148 namespaceUri() and name().
149
150 \value Characters The reader reports characters in text(). If the
151 characters are all white-space, isWhitespace() returns \c true. If
152 the characters stem from a CDATA section, isCDATA() returns \c true.
153
154 \value Comment The reader reports a comment in text().
155
156 \value DTD The reader reports a DTD in text(), notation
157 declarations in notationDeclarations(), and entity declarations in
158 entityDeclarations(). Details of the DTD declaration are reported
159 in dtdName(), dtdPublicId(), and dtdSystemId().
160
161 \value EntityReference The reader reports an entity reference that
162 could not be resolved. The name of the reference is reported in
163 name(), the replacement text in text().
164
165 \value ProcessingInstruction The reader reports a processing
166 instruction in processingInstructionTarget() and
167 processingInstructionData().
168*/
169
170/*!
171 \enum QXmlStreamReader::ReadElementTextBehaviour
172
173 This enum specifies the different behaviours of readElementText().
174
175 \value ErrorOnUnexpectedElement Raise an UnexpectedElementError and return
176 what was read so far when a child element is encountered.
177
178 \value IncludeChildElements Recursively include the text from child elements.
179
180 \value SkipChildElements Skip child elements.
181
182 \since 4.6
183*/
184
185/*!
186 \enum QXmlStreamReader::Error
187
188 This enum specifies different error cases
189
190 \value NoError No error has occurred.
191
192 \value CustomError A custom error has been raised with
193 raiseError()
194
195 \value NotWellFormedError The parser internally raised an error
196 due to the read XML not being well-formed.
197
198 \value PrematureEndOfDocumentError The input stream ended before a
199 well-formed XML document was parsed. Recovery from this error is
200 possible if more XML arrives in the stream, either by calling
201 addData() or by waiting for it to arrive on the device().
202
203 \value UnexpectedElementError The parser encountered an element
204 or token that was different to those it expected.
205
206*/
207
208/*!
209 \class QXmlStreamEntityResolver
210 \inmodule QtCore
211 \reentrant
212 \since 4.4
213
214 \brief The QXmlStreamEntityResolver class provides an entity
215 resolver for a QXmlStreamReader.
216
217 \ingroup xml-tools
218
219 Use to inform QXmlStreamReader how to expand entities not
220 \l{QXmlStreamReader::entityDeclarations()}{declared in the internal-set of
221 the DTD}.
222
223 \target sec-con-QXmlStreamEntityResolver
224 \section1 Security Considerations
225
226 \target sec-con-QXmlStreamEntityResolver-cycles
227 \section2 Entity Cycles
228
229 You must take care to avoid resolving entities in cycles, because
230 QXmlStreamReader only detects and rejects cycles in
231 \l{QXmlStreamReader::entityDeclarations()}{entities defined in the DTD},
232 not in entities expanded from an implementation of the
233 QXmlStreamEntityResolver interface.
234
235 This is by design: QXmlStreamReader puts the work on the implementation of
236 a concrete QXmlStreamEntityResolver. For static mappings, like
237 \l{https://www.w3.org/TR/xml-entity-names/}{XML Entity Definitions for
238 Characters}, this is trivially guaranteed, so running some tracking in the
239 background would just slow things down for everyone.
240
241 Things get interesting when you read entity definitions from external
242 input, including untrusted sources. In this case, \e{your implementation}
243 must ensure the expansions it uses as input are cycle-free. This is a
244 \l{https://en.wikipedia.org/wiki/Cycle_(graph_theory)#Cycle_detection}{simple
245 graph operation} that can be implemented in linear time and space and can
246 be performed up front at load time, so it doesn't affect
247 resolveUndeclaredEntity() performance.
248
249 \target sec-con-QXmlStreamEntityResolver-expansion-limit
250 \section2 Entity Expansion Limit
251
252 At the moment, entities resolved by this class do not count against
253 QXmlStreamReader::entityExpansionLimit(). This may change in future
254 versions of Qt.
255
256 For the time being, you need to enforce some upper expansion limit
257 yourself, if you read entity definitions from external input. After cycle
258 detection,
259 \l{https://en.wikipedia.org/wiki/Longest_path_problem#Acyclic_graphs}{longest-path
260 calculation} is a simple graph operation that can be implemented in linear
261 time and space and can be performed up front at load time, so it, too,
262 doesn't affect resolveUndeclaredEntity() performance.
263
264 \sa QXmlStreamReader::setEntityResolver()
265 */
266
267/*!
268 Destroys the entity resolver.
269 */
270QXmlStreamEntityResolver::~QXmlStreamEntityResolver()
271{
272}
273
274/*!
275 \internal
276
277This function is a stub for later functionality.
278*/
279QString QXmlStreamEntityResolver::resolveEntity(const QString& /*publicId*/, const QString& /*systemId*/)
280{
281 Q_UNIMPLEMENTED();
282 return QString();
283}
284
285
286/*!
287 Reimplement this function to resolve the undeclared entity \a name and
288 return its replacement text. If the entity is unknown to the entity
289 resolver, return a \l{QString::isNull()}{null string}: \c{QString()}. This
290 will raise an error in QXmlStreamreader. An empty, but non-null string is
291 considered a valid expansion of the entity, and will not cause an error.
292
293 The default implementation always returns \c{QString()}.
294*/
295
296QString QXmlStreamEntityResolver::resolveUndeclaredEntity(const QString &/*name*/)
297{
298 return QString();
299}
300
301#if QT_CONFIG(xmlstreamreader)
302
303QString QXmlStreamReaderPrivate::resolveUndeclaredEntity(const QString &name)
304{
305 if (entityResolver)
306 return entityResolver->resolveUndeclaredEntity(name);
307 return QString();
308}
309
310
311
312/*!
313 \since 4.4
314
315 Makes \a resolver the new entityResolver().
316
317 The stream reader does \e not take ownership of the resolver. It's
318 the callers responsibility to ensure that the resolver is valid
319 during the entire life-time of the stream reader object, or until
320 another resolver or \nullptr is set.
321
322 \sa entityResolver()
323 */
324void QXmlStreamReader::setEntityResolver(QXmlStreamEntityResolver *resolver)
325{
326 Q_D(QXmlStreamReader);
327 d->entityResolver = resolver;
328}
329
330/*!
331 \since 4.4
332
333 Returns the entity resolver, or \nullptr if there is no entity resolver.
334
335 \sa setEntityResolver()
336 */
337QXmlStreamEntityResolver *QXmlStreamReader::entityResolver() const
338{
339 Q_D(const QXmlStreamReader);
340 return d->entityResolver;
341}
342
343
344
345/*!
346 \class QXmlStreamReader
347 \inmodule QtCore
348 \reentrant
349 \since 4.3
350
351 \brief The QXmlStreamReader class provides a fast parser for reading
352 XML 1.0 documents via a simple streaming API.
353
354
355 \ingroup xml-tools
356
357 \ingroup qtserialization
358
359 QXmlStreamReader provides a simple streaming API to parse
360 XML 1.0 documents. It is an alternative to first loading the complete
361 XML into a DOM tree (see \l QDomDocument). QXmlStreamReader reads data
362 either from a QIODevice (see setDevice()), or from a raw QByteArray
363 (see addData()).
364
365 \note QXmlStreamReader supports only XML version 1.0. Documents declaring
366 any other version, such as "1.1", will result in a parsing error.
367
368 Qt provides QXmlStreamWriter for writing XML.
369
370 The basic concept of a stream reader is to report an XML document as
371 a stream of tokens, similar to SAX. The main difference between
372 QXmlStreamReader and SAX is \e how these XML tokens are reported.
373 With SAX, the application must provide handlers (callback functions)
374 that receive so-called XML \e events from the parser at the parser's
375 convenience. With QXmlStreamReader, the application code itself
376 drives the loop and pulls \e tokens from the reader, one after
377 another, as it needs them. This is done by calling readNext(), where
378 the reader reads from the input stream until it completes the next
379 token, at which point it returns the tokenType(). A set of
380 convenient functions including isStartElement() and text() can then
381 be used to examine the token to obtain information about what has
382 been read. The big advantage of this \e pulling approach is the
383 possibility to build recursive descent parsers with it, meaning you
384 can split your XML parsing code easily into different methods or
385 classes. This makes it easy to keep track of the application's own
386 state when parsing XML.
387
388 A typical loop with QXmlStreamReader looks like this:
389
390 \snippet code/src_corelib_xml_qxmlstream.cpp 0
391
392
393 QXmlStreamReader is a \l{https://www.w3.org/TR/xml/#proc-types}{non-validating},
394 forward-only XML 1.0 parser. It does \e not process external parsed
395 entities or perform DTD validation.
396 As long as no error occurs, the application can rely on the
397 following guarantees:
398 \list
399 \li The XML content satisfies the W3C's criteria for
400 well-formed XML 1.0
401 \li References to internal entities are replaced with the correct
402 replacement text.
403 \li Attributes are normalized or added according to the
404 internal \l DTD subset.
405 \li Tokens are provided in the correct order for a well-formed
406 document.
407 \li A \l StartDocument token (if present) appears before all
408 other elements, aside from comments and processing instructions.
409 \li At most one DOCTYPE element (a token of type \l DTD) is present,
410 and if so, it appears before any other content (aside from
411 StartDocument, comments, and processing instructions).
412 \endlist
413
414 In particular, once any token of type \l StartElement, \l EndElement,
415 \l Characters, \l EntityReference or \l EndDocument is seen, no
416 tokens of type StartDocument or DTD will be seen. If one is present in
417 the input stream, out of order, an error is raised.
418
419 \note The token types \l Comment and \l ProcessingInstruction may appear
420 anywhere in the stream.
421
422 If an error occurs while parsing, atEnd() and hasError() return
423 true, and error() returns the error that occurred. The functions
424 errorString(), lineNumber(), columnNumber(), and characterOffset()
425 are for constructing an appropriate error or warning message. To
426 simplify application code, QXmlStreamReader contains a raiseError()
427 mechanism that lets you raise custom errors that trigger the same
428 error handling described.
429
430 The \l{QXmlStream Bookmarks Example} illustrates how to use the
431 recursive descent technique to read an XML bookmark file (XBEL) with
432 a stream reader.
433
434 \section1 Namespaces
435
436 QXmlStream understands and resolves XML namespaces. E.g. in case of
437 a StartElement, namespaceUri() returns the namespace the element is
438 in, and name() returns the element's \e local name. The combination
439 of namespaceUri and name uniquely identifies an element. If a
440 namespace prefix was not declared in the XML entities parsed by the
441 reader, the namespaceUri is empty.
442
443 If you parse XML data that does not utilize namespaces according to
444 the XML specification or doesn't use namespaces at all, you can use
445 the element's qualifiedName() instead. A qualified name is the
446 element's prefix() followed by colon followed by the element's local
447 name() - exactly like the element appears in the raw XML data. Since
448 the mapping namespaceUri to prefix is neither unique nor universal,
449 qualifiedName() should be avoided for namespace-compliant XML data.
450
451 In order to parse standalone documents that do use undeclared
452 namespace prefixes, you can turn off namespace processing completely
453 with the \l namespaceProcessing property.
454
455 \section1 Incremental Parsing
456
457 QXmlStreamReader is an incremental parser. It can handle the case
458 where the document can't be parsed all at once because it arrives in
459 chunks (e.g. from multiple files, or over a network connection).
460 When the reader runs out of data before the complete document has
461 been parsed, it reports a PrematureEndOfDocumentError. When more
462 data arrives, either because of a call to addData() or because more
463 data is available through the network device(), the reader recovers
464 from the PrematureEndOfDocumentError error and continues parsing the
465 new data with the next call to readNext().
466
467 For example, if your application reads data from the network using a
468 \l{QNetworkAccessManager} {network access manager}, you would issue
469 a \l{QNetworkRequest} {network request} to the manager and receive a
470 \l{QNetworkReply} {network reply} in return. Since a QNetworkReply
471 is a QIODevice, you connect its \l{QIODevice::readyRead()}
472 {readyRead()} signal to a custom slot, e.g. \c{slotReadyRead()} in
473 the code snippet shown in the discussion for QNetworkAccessManager.
474 In this slot, you read all available data with
475 \l{QIODevice::readAll()} {readAll()} and pass it to the XML
476 stream reader using addData(). Then you call your custom parsing
477 function that reads the XML events from the reader.
478
479 \section1 Performance and Memory Consumption
480
481 QXmlStreamReader is memory-conservative by design, since it doesn't
482 store the entire XML document tree in memory, but only the current
483 token at the time it is reported. In addition, QXmlStreamReader
484 avoids the many small string allocations that it normally takes to
485 map an XML document to a convenient and Qt-ish API. It does this by
486 reporting all string data as QStringView rather than real QString
487 objects. Calling \l{QStringView::toString()}{toString()} on any of
488 those objects returns an equivalent real QString object.
489*/
490
491Q_DECL_COLD_FUNCTION
492static void warn_addData_with_device()
493{
494 qWarning("QXmlStreamReader: addData() with device()");
495}
496
497/*!
498 Constructs a stream reader.
499
500 \sa setDevice(), addData()
501 */
502QXmlStreamReader::QXmlStreamReader()
503 : d_ptr(new QXmlStreamReaderPrivate(this))
504{
505}
506
507/*! Creates a new stream reader that reads from \a device.
508
509\sa setDevice(), clear()
510 */
511QXmlStreamReader::QXmlStreamReader(QIODevice *device)
512 : d_ptr(new QXmlStreamReaderPrivate(this))
513{
514 setDevice(device);
515}
516
517/*!
518 \overload
519
520 \fn QXmlStreamReader::QXmlStreamReader(const QByteArray &data)
521
522 Creates a new stream reader that reads from \a data.
523
524 \sa addData(), clear(), setDevice()
525*/
526
527/*!
528 \internal
529
530 Append a chunk \a data which uses \a enc as encoding.
531
532 Passing \l QStringDecoder::System as \a enc means that the encoding is
533 unknown and a document-global decoder should be used. Otherwise, a
534 chunk decoder with the specified encoding will be created and used, so
535 the document-global decoder will not be used and/or modified.
536*/
537void QXmlStreamReaderPrivate::appendDataWithEncoding(const QByteArray &data,
538 QStringDecoder::Encoding enc)
539{
540 if (tryAppendViewWithEncoding(data, enc))
541 return;
542 dataInfo.emplace_back(data, enc);
543}
544
545bool QXmlStreamReaderPrivate::tryAppendViewWithEncoding(QByteArrayView data, QStringDecoder::Encoding enc)
546{
547 if (data.isEmpty())
548 return true;
549 // Joining the buffers might be useful for a stateful decoder, or when
550 // e == System, meaning that we have to try to guess the decoder
551 if (!dataInfo.empty()) {
552 auto &last = dataInfo.back();
553 if (last.encoding == enc) {
554 last.buffer.append(data);
555 return true;
556 }
557 }
558 return false;
559}
560
561void QXmlStreamReaderPrivate::appendViewWithEncoding(QByteArrayView data, QStringDecoder::Encoding enc)
562{
563 if (tryAppendViewWithEncoding(data, enc))
564 return;
565 dataInfo.emplace_back(data.toByteArray(), enc);
566}
567
568/*!
569 Creates a new stream reader that reads from \a data.
570
571 \note In Qt versions prior to 6.5, this constructor was overloaded
572 for QString and \c {const char*}.
573
574 \sa addData(), clear(), setDevice()
575*/
576QXmlStreamReader::QXmlStreamReader(QAnyStringView data)
577 : d_ptr(new QXmlStreamReaderPrivate(this))
578{
579 addData(data);
580}
581
582/*!
583 \internal
584
585 Creates a new stream reader that reads from \a data.
586 Used by the weak constructor taking a QByteArray.
587*/
588QXmlStreamReader::QXmlStreamReader(const QByteArray &data, PrivateConstructorTag)
589 : d_ptr(new QXmlStreamReaderPrivate(this))
590{
591 Q_D(QXmlStreamReader);
592 d->appendDataWithEncoding(data, QStringDecoder::System);
593}
594
595/*!
596 Destructs the reader.
597 */
598QXmlStreamReader::~QXmlStreamReader()
599{
600 Q_D(QXmlStreamReader);
601 if (d->deleteDevice)
602 delete d->device;
603}
604
605/*! \fn bool QXmlStreamReader::hasError() const
606 Returns \c true if an error has occurred, otherwise \c false.
607
608 \sa errorString(), error()
609 */
610
611/*!
612 Sets the current device to \a device. Setting the device resets
613 the stream to its initial state.
614
615 \sa device(), clear()
616*/
617void QXmlStreamReader::setDevice(QIODevice *device)
618{
619 Q_D(QXmlStreamReader);
620 if (d->deleteDevice) {
621 delete d->device;
622 d->deleteDevice = false;
623 }
624 d->device = device;
625 d->init();
626
627}
628
629/*!
630 Returns the current device associated with the QXmlStreamReader,
631 or \nullptr if no device has been assigned.
632
633 \sa setDevice()
634*/
635QIODevice *QXmlStreamReader::device() const
636{
637 Q_D(const QXmlStreamReader);
638 return d->device;
639}
640
641/*!
642 \overload
643
644 \fn void QXmlStreamReader::addData(const QByteArray &data)
645
646 Adds more \a data for the reader to read. This function does
647 nothing if the reader has a device().
648
649 \sa readNext(), clear()
650*/
651
652static bool isDecoderForEncoding(const QStringDecoder &dec, QStringDecoder::Encoding enc)
653{
654 if (!dec.isValid())
655 return false;
656
657 const auto decName = dec.name();
658 if (!decName || !*decName) // only match when non-empty
659 return false;
660
661 const auto encName = QStringConverter::nameForEncoding(enc);
662 return encName && strcmp(decName, encName) == 0;
663}
664
665/*!
666 Adds more \a data for the reader to read. This function does
667 nothing if the reader has a device().
668
669 \note In Qt versions prior to 6.5, this function was overloaded
670 for QString and \c {const char*}.
671
672 \sa readNext(), clear()
673*/
674void QXmlStreamReader::addData(QAnyStringView data)
675{
676 Q_D(QXmlStreamReader);
677 if (d->device)
678 return warn_addData_with_device();
679 data.visit([d](auto data) {
680 d->appendViewWithEncoding(as_bytes(QSpan(data)), encodingFor<decltype(data)>);
681 });
682}
683
684/*!
685 \internal
686
687 Adds more \a data for the reader to read. This function does
688 nothing if the reader has a device().
689*/
690void QXmlStreamReader::addDataImpl(const QByteArray &data)
691{
692 Q_D(QXmlStreamReader);
693 if (d->device)
694 return warn_addData_with_device();
695 d->appendDataWithEncoding(data, QStringDecoder::System);
696}
697
698/*!
699 Removes any device() or data from the reader and resets its
700 internal state to the initial state.
701
702 \sa addData()
703 */
704void QXmlStreamReader::clear()
705{
706 Q_D(QXmlStreamReader);
707 d->init();
708 if (d->device) {
709 if (d->deleteDevice)
710 delete d->device;
711 d->device = nullptr;
712 }
713}
714
715/*!
716 Returns \c true if the reader has read until the end of the XML
717 document, or if an error() has occurred and reading has been
718 aborted. Otherwise, it returns \c false.
719
720 When atEnd() and hasError() return true and error() returns
721 PrematureEndOfDocumentError, it means the XML has been well-formed
722 so far, but a complete XML document has not been parsed. The next
723 chunk of XML can be added with addData(), if the XML is being read
724 from a QByteArray, or by waiting for more data to arrive if the
725 XML is being read from a QIODevice. Either way, atEnd() will
726 return false once more data is available.
727
728 \sa hasError(), error(), device(), QIODevice::atEnd()
729 */
730bool QXmlStreamReader::atEnd() const
731{
732 Q_D(const QXmlStreamReader);
733 if (d->atEnd
734 && ((d->type == QXmlStreamReader::Invalid && d->error == PrematureEndOfDocumentError)
735 || (d->type == QXmlStreamReader::EndDocument))) {
736 if (d->device)
737 return d->device->atEnd();
738 else
739 return d->dataInfo.empty();
740 }
741 return (d->atEnd || d->type == QXmlStreamReader::Invalid);
742}
743
744
745/*!
746 Reads the next token and returns its type.
747
748 With one exception, once an error() is reported by readNext(),
749 further reading of the XML stream is not possible. Then atEnd()
750 returns \c true, hasError() returns \c true, and this function returns
751 QXmlStreamReader::Invalid.
752
753 The exception is when error() returns PrematureEndOfDocumentError.
754 This error is reported when the end of an otherwise well-formed
755 chunk of XML is reached, but the chunk doesn't represent a complete
756 XML document. In that case, parsing \e can be resumed by calling
757 addData() to add the next chunk of XML, when the stream is being
758 read from a QByteArray, or by waiting for more data to arrive when
759 the stream is being read from a device().
760
761 \sa tokenType(), tokenString()
762 */
763QXmlStreamReader::TokenType QXmlStreamReader::readNext()
764{
765 Q_D(QXmlStreamReader);
766 if (d->type != Invalid) {
767 if (!d->hasCheckedStartDocument)
768 if (!d->checkStartDocument())
769 return d->type; // synthetic StartDocument or error
770 d->parse();
771 if (d->atEnd && d->type != EndDocument && d->type != Invalid)
772 d->raiseError(PrematureEndOfDocumentError);
773 else if (!d->atEnd && d->type == EndDocument)
774 d->raiseWellFormedError(QXmlStream::tr("Extra content at end of document."));
775 } else if (d->error == PrematureEndOfDocumentError) {
776 // resume error
777 d->type = NoToken;
778 d->atEnd = false;
779 d->token = -1;
780 return readNext();
781 }
782 d->checkToken();
783 return d->type;
784}
785
786
787/*!
788 Returns the type of the current token.
789
790 The current token can also be queried with the convenience functions
791 isStartDocument(), isEndDocument(), isStartElement(),
792 isEndElement(), isCharacters(), isComment(), isDTD(),
793 isEntityReference(), and isProcessingInstruction().
794
795 \sa tokenString()
796 */
797QXmlStreamReader::TokenType QXmlStreamReader::tokenType() const
798{
799 Q_D(const QXmlStreamReader);
800 return d->type;
801}
802
803/*!
804 Reads until the next start element within the current element. Returns \c true
805 when a start element was reached. When the end element was reached, or when
806 an error occurred, false is returned.
807
808 The current element is the element matching the most recently parsed start
809 element of which a matching end element has not yet been reached. When the
810 parser has reached the end element, the current element becomes the parent
811 element.
812
813 This is a convenience function for when you're only concerned with parsing
814 XML elements. The \l{QXmlStream Bookmarks Example} makes extensive use of
815 this function.
816
817 \since 4.6
818 \sa readNext()
819 */
820bool QXmlStreamReader::readNextStartElement()
821{
822 while (readNext() != Invalid) {
823 if (isEndElement() || isEndDocument())
824 return false;
825 else if (isStartElement())
826 return true;
827 }
828 return false;
829}
830
831/*!
832 Reads until the end of the current element, skipping any child nodes.
833 This function is useful for skipping unknown elements.
834
835 The current element is the element matching the most recently parsed start
836 element of which a matching end element has not yet been reached. When the
837 parser has reached the end element, the current element becomes the parent
838 element.
839
840 \since 4.6
841 */
842void QXmlStreamReader::skipCurrentElement()
843{
844 int depth = 1;
845 while (depth && readNext() != Invalid) {
846 if (isEndElement())
847 --depth;
848 else if (isStartElement())
849 ++depth;
850 }
851}
852
853/*!
854 Reads and returns the raw inner XML content of the current element.
855 This function is useful for retrieving the full contents embedded inside
856 an element, including nested tags, text, comments, processing instructions,
857 CDATA sections, and other markup — preserving the original XML structure.
858
859 The current element is the element matching the most recently parsed start
860 element of which a matching end element has not yet been reached. When the
861 parser has reached the end element, the current element becomes the parent
862 element.
863
864 \note Entity references defined in the DTD are resolved during parsing
865 and returned as plain text, since DTD declarations are processed
866 separately and are not part of the element’s content.
867 Only the five predefined XML entities (\c &lt;, \c &gt;, \c &amp;,
868 \c &apos;, \c &quot;) are re-escaped in the output.
869
870 \since 6.10
871*/
872QString QXmlStreamReader::readRawInnerData()
873{
874 Q_D(QXmlStreamReader);
875 QString raw;
876
877 auto specialToEntities = [](QStringView text, QString &output) {
878 qsizetype chunk = 0;
879 QLatin1StringView replacement;
880 const qsizetype sz = text.size();
881 for (qsizetype i = 0; i < sz; ++i) {
882 switch (text[i].unicode()) {
883 case '<':
884 replacement = "&lt;"_L1;
885 break;
886 case '>':
887 replacement = "&gt;"_L1;
888 break;
889 case '&':
890 replacement = "&amp;"_L1;
891 break;
892 case '"':
893 replacement = "&quot;"_L1;
894 break;
895 case '\'':
896 replacement = "&apos;"_L1;
897 break;
898 default:
899 continue;
900 }
901 if (chunk < i)
902 output += text.mid(chunk, i - chunk);
903 output += replacement;
904 chunk = i + 1;
905 }
906 if (chunk < text.size())
907 output += text.mid(chunk);
908 };
909
910 if (isStartElement()) {
911 int depth = 1;
912 while (!atEnd() && depth) {
913 switch (readNext()) {
914 case StartElement: {
915 raw += '<'_L1 + name();
916 const QXmlStreamAttributes attrs = attributes();
917 for (auto it = attrs.begin(); it != attrs.end(); ++it) {
918 raw += ' '_L1 + it->name() + "=\""_L1;
919 specialToEntities(it->value(), raw);
920 raw += '"'_L1;
921 }
922 raw += '>'_L1;
923 ++depth;
924 break;
925 }
926 case EndElement:
927 --depth;
928 if (depth > 0)
929 raw += "</"_L1 + name() + '>'_L1;
930 break;
931 case Characters:
932 if (isCDATA())
933 raw += "<![CDATA["_L1 + text() + "]]>"_L1;
934 else
935 specialToEntities(text(), raw);
936 break;
937 case Comment:
938 raw += "<!--"_L1 + text() + "-->"_L1;
939 break;
940 case EntityReference:
941 raw += '&'_L1 + name() + ';'_L1;
942 break;
943 case ProcessingInstruction:
944 raw += "<?"_L1 + processingInstructionTarget()
945 + ' '_L1 + processingInstructionData()
946 + "?>"_L1;
947 break;
948 Q_FALLTHROUGH();
949 default:
950 if (!hasError()) {
951 d->raiseError(NotWellFormedError,
952 QXmlStream::tr("Unexpected token while "
953 "reading raw inner data."));
954 }
955 return raw;
956 }
957 }
958 }
959 return raw;
960}
961
962static constexpr auto QXmlStreamReader_tokenTypeString = qOffsetStringArray(
963 "NoToken",
964 "Invalid",
965 "StartDocument",
966 "EndDocument",
967 "StartElement",
968 "EndElement",
969 "Characters",
970 "Comment",
971 "DTD",
972 "EntityReference",
973 "ProcessingInstruction"
974);
975
976static constexpr auto QXmlStreamReader_XmlContextString = qOffsetStringArray(
977 "Prolog",
978 "Body"
979);
980
981/*!
982 \property QXmlStreamReader::namespaceProcessing
983 \brief the namespace-processing flag of the stream reader.
984
985 This property controls whether or not the stream reader processes
986 namespaces. If enabled, the reader processes namespaces, otherwise
987 it does not.
988
989 By default, namespace-processing is enabled.
990*/
991
992
993void QXmlStreamReader::setNamespaceProcessing(bool enable)
994{
995 Q_D(QXmlStreamReader);
996 d->namespaceProcessing = enable;
997}
998
999bool QXmlStreamReader::namespaceProcessing() const
1000{
1001 Q_D(const QXmlStreamReader);
1002 return d->namespaceProcessing;
1003}
1004
1005/*! Returns the reader's current token as string.
1006
1007\sa tokenType()
1008*/
1009QString QXmlStreamReader::tokenString() const
1010{
1011 Q_D(const QXmlStreamReader);
1012 return QLatin1StringView(QXmlStreamReader_tokenTypeString.at(d->type));
1013}
1014
1015/*!
1016 \internal
1017 \return \param ctxt (Prolog/Body) as a string.
1018 */
1019static constexpr QLatin1StringView contextString(QXmlStreamReaderPrivate::XmlContext ctxt)
1020{
1021 return QLatin1StringView(QXmlStreamReader_XmlContextString.viewAt(static_cast<int>(ctxt)));
1022}
1023
1024#endif // feature xmlstreamreader
1025
1026QXmlStreamPrivateTagStack::QXmlStreamPrivateTagStack()
1027{
1028 tagStack.reserve(16);
1029 tagStackStringStorageSize = 0;
1030 NamespaceDeclaration &namespaceDeclaration = namespaceDeclarations.push();
1031 namespaceDeclaration.namespaceUri = addToStringStorage(u"http://www.w3.org/XML/1998/namespace");
1032 namespaceDeclaration.prefix = addToStringStorage(u"xml");
1033 initialTagStackStringStorageSize = tagStackStringStorageSize;
1034 tagsDone = false;
1035}
1036
1037#if QT_CONFIG(xmlstreamreader)
1038
1039QXmlStreamReaderPrivate::QXmlStreamReaderPrivate(QXmlStreamReader *q)
1040 :q_ptr(q)
1041{
1042 device = nullptr;
1043 deleteDevice = false;
1044 stack_size = 64;
1045 sym_stack = nullptr;
1046 state_stack = nullptr;
1047 reallocateStack();
1048 entityResolver = nullptr;
1049 init();
1050}
1051
1052void QXmlStreamReaderPrivate::init()
1053{
1054 entityHash.clear();
1055#define ADD_PREDEFINED(n, v)
1056 do {
1057 Entity e = Entity::createLiteral(n##_L1, v##_L1);
1058 entityHash.insert(qToStringViewIgnoringNull(e.name), std::move(e));
1059 } while (false)
1060 ADD_PREDEFINED("lt", "<");
1061 ADD_PREDEFINED("gt", ">");
1062 ADD_PREDEFINED("amp", "&");
1063 ADD_PREDEFINED("apos", "'");
1064 ADD_PREDEFINED("quot", "\"");
1065#undef ADD_PREDEFINED
1066 parameterEntityHash.clear();
1067 dtdAttributes.clear();
1068 scanDtd = false;
1069 lastAttributeIsCData = false;
1070 token = -1;
1071 token_char = 0;
1072 isEmptyElement = false;
1073 isWhitespace = true;
1074 isCDATA = false;
1075 standalone = false;
1076 hasStandalone = false;
1077 tos = 0;
1078 resumeReduction = 0;
1079 state_stack[tos++] = 0;
1080 state_stack[tos] = 0;
1081 putStack.clear();
1082 putStack.reserve(32);
1083 dtdName.clear();
1084 dtdPublicId.clear();
1085 dtdSystemId.clear();
1086 dtdInternalSubsetValue.clear();
1087 entityDeclarations.clear();
1088 entityDeclarations.reserve(16);
1089 publicEntityDeclarations.clear();
1090 notationDeclarations.clear();
1091 notationDeclarations.reserve(16);
1092 publicNotationDeclarations.clear();
1093 textBuffer.clear();
1094 textBuffer.reserve(256);
1095 tagStack.clear();
1096 tagsDone = false;
1097 attributes.clear();
1098 attributes.reserve(16);
1099 lineNumber = lastLineStart = characterOffset = 0;
1100 readBufferPos = 0;
1101 nbytesread = 0;
1102 decoder = QStringDecoder();
1103 attributeStack.clear();
1104 attributeStack.reserve(16);
1105 entityReferenceStack.clear();
1106 entityReferenceStack.reserve(16);
1107 entityLength = 0;
1108 entityParser.reset();
1109 hasCheckedStartDocument = false;
1110 normalizeLiterals = false;
1111 hasSeenTag = false;
1112 atEnd = false;
1113 inParseEntity = false;
1114 referenceToUnparsedEntityDetected = false;
1115 referenceToParameterEntityDetected = false;
1116 hasExternalDtdSubset = false;
1117 lockEncoding = false;
1118 namespaceProcessing = true;
1119 rawReadBuffer.clear();
1120 chunkDecoder = QStringDecoder();
1121 dataInfo.clear();
1122 readBuffer.clear();
1123 tagStackStringStorageSize = initialTagStackStringStorageSize;
1124
1125 type = QXmlStreamReader::NoToken;
1126 error = QXmlStreamReader::NoError;
1127 currentContext = XmlContext::Prolog;
1128 foundDTD = false;
1129}
1130
1131/*
1132 Well-formed requires that we verify entity values. We do this with a
1133 standard parser.
1134 */
1135void QXmlStreamReaderPrivate::parseEntity(const QString &value)
1136{
1137 Q_Q(QXmlStreamReader);
1138
1139 if (value.isEmpty())
1140 return;
1141
1142
1143 if (!entityParser)
1144 entityParser = std::make_unique<QXmlStreamReaderPrivate>(q);
1145 else
1146 entityParser->init();
1147 entityParser->inParseEntity = true;
1148 entityParser->readBuffer = value;
1149 entityParser->injectToken(PARSE_ENTITY);
1150 while (!entityParser->atEnd && entityParser->type != QXmlStreamReader::Invalid)
1151 entityParser->parse();
1152 if (entityParser->type == QXmlStreamReader::Invalid || entityParser->tagStack.size())
1153 raiseWellFormedError(QXmlStream::tr("Invalid entity value."));
1154
1155}
1156
1157inline void QXmlStreamReaderPrivate::reallocateStack()
1158{
1159 // The multiplication cannot overflow (we would have alloc'ed more than
1160 // half of the address space using the realloc()s below, before that
1161 // happens):
1162 const auto newStackSize = stack_size * 2;
1163
1164 void *p = qt_reallocarray(sym_stack, size_t(newStackSize), sizeof(Value));
1165 Q_CHECK_PTR(p);
1166 sym_stack = static_cast<Value*>(p);
1167 p = qt_reallocarray(state_stack, size_t(newStackSize), sizeof(int));
1168 Q_CHECK_PTR(p);
1169 state_stack = static_cast<int*>(p);
1170
1171 // only update this after _both_ allocations succeeded:
1172 stack_size = newStackSize;
1173}
1174
1175
1176QXmlStreamReaderPrivate::~QXmlStreamReaderPrivate()
1177{
1178 free(sym_stack);
1179 free(state_stack);
1180}
1181
1182
1183inline uint QXmlStreamReaderPrivate::filterCarriageReturn()
1184{
1185 uint peekc = peekChar();
1186 if (peekc == '\n') {
1187 if (putStack.size())
1188 putStack.pop();
1189 else
1190 ++readBufferPos;
1191 return peekc;
1192 }
1193 if (peekc == StreamEOF) {
1194 putChar('\r');
1195 return 0;
1196 }
1197 return '\n';
1198}
1199
1200/*!
1201 \internal
1202 If the end of the file is encountered, ~0 is returned.
1203 */
1204inline uint QXmlStreamReaderPrivate::getChar()
1205{
1206 uint c;
1207 if (putStack.size()) {
1208 c = atEnd ? StreamEOF : putStack.pop();
1209 } else {
1210 if (readBufferPos < readBuffer.size())
1211 c = readBuffer.at(readBufferPos++).unicode();
1212 else
1213 c = getChar_helper();
1214 }
1215
1216 return c;
1217}
1218
1219inline uint QXmlStreamReaderPrivate::peekChar()
1220{
1221 uint c;
1222 if (putStack.size()) {
1223 c = putStack.top();
1224 } else if (readBufferPos < readBuffer.size()) {
1225 c = readBuffer.at(readBufferPos).unicode();
1226 } else {
1227 if ((c = getChar_helper()) != StreamEOF)
1228 --readBufferPos;
1229 }
1230
1231 return c;
1232}
1233
1234/*!
1235 \internal
1236
1237 Scans characters until \a str is encountered, and validates the characters
1238 as according to the Char[2] production and do the line-ending normalization.
1239 If any character is invalid, false is returned, otherwise true upon success.
1240
1241 If \a tokenToInject is not less than zero, injectToken() is called with
1242 \a tokenToInject when \a str is found.
1243
1244 If any error occurred, false is returned, otherwise true.
1245 */
1246bool QXmlStreamReaderPrivate::scanUntil(const char *str, short tokenToInject)
1247{
1248 const qsizetype pos = textBuffer.size();
1249 const auto oldLineNumber = lineNumber;
1250
1251 uint c;
1252 while ((c = getChar()) != StreamEOF) {
1253 /* First, we do the validation & normalization. */
1254 switch (c) {
1255 case '\r':
1256 if ((c = filterCarriageReturn()) == 0)
1257 break;
1258 Q_FALLTHROUGH();
1259 case '\n':
1260 ++lineNumber;
1261 lastLineStart = characterOffset + readBufferPos;
1262 Q_FALLTHROUGH();
1263 case '\t':
1264 textBuffer += QChar(c);
1265 continue;
1266 default:
1267 if (c < 0x20 || (c > 0xFFFD && c < 0x10000) || c > QChar::LastValidCodePoint ) {
1268 raiseWellFormedError(QXmlStream::tr("Invalid XML character."));
1269 lineNumber = oldLineNumber;
1270 return false;
1271 }
1272 textBuffer += QChar(c);
1273 }
1274
1275
1276 /* Second, attempt to lookup str. */
1277 if (c == uint(*str)) {
1278 if (!*(str + 1)) {
1279 if (tokenToInject >= 0)
1280 injectToken(tokenToInject);
1281 return true;
1282 } else {
1283 if (scanString(str + 1, tokenToInject, false))
1284 return true;
1285 }
1286 }
1287 }
1288 putString(textBuffer, pos);
1289 textBuffer.resize(pos);
1290 lineNumber = oldLineNumber;
1291 return false;
1292}
1293
1294bool QXmlStreamReaderPrivate::scanString(const char *str, short tokenToInject, bool requireSpace)
1295{
1296 qsizetype n = 0;
1297 while (str[n]) {
1298 uint c = getChar();
1299 if (c != ushort(str[n])) {
1300 if (c != StreamEOF)
1301 putChar(c);
1302 while (n--) {
1303 putChar(ushort(str[n]));
1304 }
1305 return false;
1306 }
1307 ++n;
1308 }
1309 textBuffer += QLatin1StringView(str, n);
1310 if (requireSpace) {
1311 const qsizetype s = fastScanSpace();
1312 if (!s || atEnd) {
1313 qsizetype pos = textBuffer.size() - n - s;
1314 putString(textBuffer, pos);
1315 textBuffer.resize(pos);
1316 return false;
1317 }
1318 }
1319 if (tokenToInject >= 0)
1320 injectToken(tokenToInject);
1321 return true;
1322}
1323
1324bool QXmlStreamReaderPrivate::scanAfterLangleBang()
1325{
1326 switch (peekChar()) {
1327 case '[':
1328 return scanString(spell[CDATA_START], CDATA_START, false);
1329 case 'D':
1330 return scanString(spell[DOCTYPE], DOCTYPE);
1331 case 'A':
1332 return scanString(spell[ATTLIST], ATTLIST);
1333 case 'N':
1334 return scanString(spell[NOTATION], NOTATION);
1335 case 'E':
1336 if (scanString(spell[ELEMENT], ELEMENT))
1337 return true;
1338 return scanString(spell[ENTITY], ENTITY);
1339
1340 default:
1341 ;
1342 };
1343 return false;
1344}
1345
1346bool QXmlStreamReaderPrivate::scanPublicOrSystem()
1347{
1348 switch (peekChar()) {
1349 case 'S':
1350 return scanString(spell[SYSTEM], SYSTEM);
1351 case 'P':
1352 return scanString(spell[PUBLIC], PUBLIC);
1353 default:
1354 ;
1355 }
1356 return false;
1357}
1358
1359bool QXmlStreamReaderPrivate::scanNData()
1360{
1361 if (fastScanSpace()) {
1362 if (scanString(spell[NDATA], NDATA))
1363 return true;
1364 putChar(' ');
1365 }
1366 return false;
1367}
1368
1369bool QXmlStreamReaderPrivate::scanAfterDefaultDecl()
1370{
1371 switch (peekChar()) {
1372 case 'R':
1373 return scanString(spell[REQUIRED], REQUIRED, false);
1374 case 'I':
1375 return scanString(spell[IMPLIED], IMPLIED, false);
1376 case 'F':
1377 return scanString(spell[FIXED], FIXED, false);
1378 default:
1379 ;
1380 }
1381 return false;
1382}
1383
1384bool QXmlStreamReaderPrivate::scanAttType()
1385{
1386 switch (peekChar()) {
1387 case 'C':
1388 return scanString(spell[CDATA], CDATA);
1389 case 'I':
1390 if (scanString(spell[ID], ID))
1391 return true;
1392 if (scanString(spell[IDREF], IDREF))
1393 return true;
1394 return scanString(spell[IDREFS], IDREFS);
1395 case 'E':
1396 if (scanString(spell[ENTITY], ENTITY))
1397 return true;
1398 return scanString(spell[ENTITIES], ENTITIES);
1399 case 'N':
1400 if (scanString(spell[NOTATION], NOTATION))
1401 return true;
1402 if (scanString(spell[NMTOKEN], NMTOKEN))
1403 return true;
1404 return scanString(spell[NMTOKENS], NMTOKENS);
1405 default:
1406 ;
1407 }
1408 return false;
1409}
1410
1411/*!
1412 \internal
1413
1414 Scan strings with quotes or apostrophes surround them. For instance,
1415 attributes, the version and encoding field in the XML prolog and
1416 entity declarations.
1417
1418 If normalizeLiterals is set to true, the function also normalizes
1419 whitespace. It is set to true when the first start tag is
1420 encountered.
1421
1422 */
1423inline qsizetype QXmlStreamReaderPrivate::fastScanLiteralContent()
1424{
1425 qsizetype n = 0;
1426 uint c;
1427 while ((c = getChar()) != StreamEOF) {
1428 switch (ushort(c)) {
1429 case 0xfffe:
1430 case 0xffff:
1431 case 0:
1432 /* The putChar() call is necessary so the parser re-gets
1433 * the character from the input source, when raising an error. */
1434 putChar(c);
1435 return n;
1436 case '\r':
1437 if (filterCarriageReturn() == 0)
1438 return n;
1439 Q_FALLTHROUGH();
1440 case '\n':
1441 ++lineNumber;
1442 lastLineStart = characterOffset + readBufferPos;
1443 Q_FALLTHROUGH();
1444 case ' ':
1445 case '\t':
1446 if (normalizeLiterals)
1447 textBuffer += u' ';
1448 else
1449 textBuffer += QChar(c);
1450 ++n;
1451 break;
1452 case '&':
1453 case '<':
1454 case '\"':
1455 case '\'':
1456 if (!(c & 0xff0000)) {
1457 putChar(c);
1458 return n;
1459 }
1460 Q_FALLTHROUGH();
1461 default:
1462 if (c < 0x20) {
1463 putChar(c);
1464 return n;
1465 }
1466 textBuffer += QChar(ushort(c));
1467 ++n;
1468 }
1469 }
1470 return n;
1471}
1472
1473inline qsizetype QXmlStreamReaderPrivate::fastScanSpace()
1474{
1475 qsizetype n = 0;
1476 uint c;
1477 while ((c = getChar()) != StreamEOF) {
1478 switch (c) {
1479 case '\r':
1480 if ((c = filterCarriageReturn()) == 0)
1481 return n;
1482 Q_FALLTHROUGH();
1483 case '\n':
1484 ++lineNumber;
1485 lastLineStart = characterOffset + readBufferPos;
1486 Q_FALLTHROUGH();
1487 case ' ':
1488 case '\t':
1489 textBuffer += QChar(c);
1490 ++n;
1491 break;
1492 default:
1493 putChar(c);
1494 return n;
1495 }
1496 }
1497 return n;
1498}
1499
1500/*!
1501 \internal
1502
1503 Used for text nodes essentially. That is, characters appearing
1504 inside elements.
1505 */
1506inline qsizetype QXmlStreamReaderPrivate::fastScanContentCharList()
1507{
1508 qsizetype n = 0;
1509 uint c;
1510 while ((c = getChar()) != StreamEOF) {
1511 switch (ushort(c)) {
1512 case 0xfffe:
1513 case 0xffff:
1514 case 0:
1515 putChar(c);
1516 return n;
1517 case ']': {
1518 isWhitespace = false;
1519 const qsizetype pos = textBuffer.size();
1520 textBuffer += QChar(ushort(c));
1521 ++n;
1522 while ((c = getChar()) == ']') {
1523 textBuffer += QChar(ushort(c));
1524 ++n;
1525 }
1526 if (c == StreamEOF) {
1527 putString(textBuffer, pos);
1528 textBuffer.resize(pos);
1529 } else if (c == '>' && textBuffer.at(textBuffer.size() - 2) == u']') {
1530 raiseWellFormedError(QXmlStream::tr("Sequence ']]>' not allowed in content."));
1531 } else {
1532 putChar(c);
1533 break;
1534 }
1535 return n;
1536 } break;
1537 case '\r':
1538 if ((c = filterCarriageReturn()) == 0)
1539 return n;
1540 Q_FALLTHROUGH();
1541 case '\n':
1542 ++lineNumber;
1543 lastLineStart = characterOffset + readBufferPos;
1544 Q_FALLTHROUGH();
1545 case ' ':
1546 case '\t':
1547 textBuffer += QChar(ushort(c));
1548 ++n;
1549 break;
1550 case '&':
1551 case '<':
1552 if (!(c & 0xff0000)) {
1553 putChar(c);
1554 return n;
1555 }
1556 Q_FALLTHROUGH();
1557 default:
1558 if (c < 0x20) {
1559 putChar(c);
1560 return n;
1561 }
1562 isWhitespace = false;
1563 textBuffer += QChar(ushort(c));
1564 ++n;
1565 }
1566 }
1567 return n;
1568}
1569
1570// Fast scan an XML attribute name (e.g. "xml:lang").
1571inline std::optional<qsizetype> QXmlStreamReaderPrivate::fastScanName(Value *val)
1572{
1573 qsizetype n = 0;
1574 uint c;
1575 while ((c = getChar()) != StreamEOF) {
1576 if (n >= 4096) {
1577 // This is too long to be a sensible name, and
1578 // can exhaust memory, or the range of decltype(*prefix)
1579 raiseNamePrefixTooLongError();
1580 return std::nullopt;
1581 }
1582 switch (c) {
1583 case '\n':
1584 case ' ':
1585 case '\t':
1586 case '\r':
1587 case '&':
1588 case '#':
1589 case '\'':
1590 case '\"':
1591 case '<':
1592 case '>':
1593 case '[':
1594 case ']':
1595 case '=':
1596 case '%':
1597 case '/':
1598 case ';':
1599 case '?':
1600 case '!':
1601 case '^':
1602 case '|':
1603 case ',':
1604 case '(':
1605 case ')':
1606 case '+':
1607 case '*':
1608 putChar(c);
1609 if (val && val->prefix == n + 1) {
1610 val->prefix = 0;
1611 putChar(':');
1612 --n;
1613 }
1614 return n;
1615 case ':':
1616 if (val) {
1617 if (val->prefix == 0) {
1618 val->prefix = qint16(n + 2);
1619 } else { // only one colon allowed according to the namespace spec.
1620 putChar(c);
1621 return n;
1622 }
1623 } else {
1624 putChar(c);
1625 return n;
1626 }
1627 Q_FALLTHROUGH();
1628 default:
1629 textBuffer += QChar(ushort(c));
1630 ++n;
1631 }
1632 }
1633
1634 if (val)
1635 val->prefix = 0;
1636 qsizetype pos = textBuffer.size() - n;
1637 putString(textBuffer, pos);
1638 textBuffer.resize(pos);
1639 return 0;
1640}
1641
1642enum NameChar { NameBeginning, NameNotBeginning, NotName };
1643
1644static const char Begi = static_cast<char>(NameBeginning);
1645static const char NtBg = static_cast<char>(NameNotBeginning);
1646static const char NotN = static_cast<char>(NotName);
1647
1648static const char nameCharTable[128] =
1649{
1650// 0x00
1651 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN,
1652 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN,
1653// 0x10
1654 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN,
1655 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN,
1656// 0x20 (0x2D is '-', 0x2E is '.')
1657 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN,
1658 NotN, NotN, NotN, NotN, NotN, NtBg, NtBg, NotN,
1659// 0x30 (0x30..0x39 are '0'..'9', 0x3A is ':')
1660 NtBg, NtBg, NtBg, NtBg, NtBg, NtBg, NtBg, NtBg,
1661 NtBg, NtBg, Begi, NotN, NotN, NotN, NotN, NotN,
1662// 0x40 (0x41..0x5A are 'A'..'Z')
1663 NotN, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1664 Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1665// 0x50 (0x5F is '_')
1666 Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1667 Begi, Begi, Begi, NotN, NotN, NotN, NotN, Begi,
1668// 0x60 (0x61..0x7A are 'a'..'z')
1669 NotN, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1670 Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1671// 0x70
1672 Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1673 Begi, Begi, Begi, NotN, NotN, NotN, NotN, NotN
1674};
1675
1676static inline NameChar fastDetermineNameChar(QChar ch)
1677{
1678 ushort uc = ch.unicode();
1679 if (!(uc & ~0x7f)) // uc < 128
1680 return static_cast<NameChar>(nameCharTable[uc]);
1681
1682 QChar::Category cat = ch.category();
1683 // ### some these categories might be slightly wrong
1684 if ((cat >= QChar::Letter_Uppercase && cat <= QChar::Letter_Other)
1685 || cat == QChar::Number_Letter)
1686 return NameBeginning;
1687 if ((cat >= QChar::Number_DecimalDigit && cat <= QChar::Number_Other)
1688 || (cat >= QChar::Mark_NonSpacing && cat <= QChar::Mark_Enclosing))
1689 return NameNotBeginning;
1690 return NotName;
1691}
1692
1693inline qsizetype QXmlStreamReaderPrivate::fastScanNMTOKEN()
1694{
1695 qsizetype n = 0;
1696 uint c;
1697 while ((c = getChar()) != StreamEOF) {
1698 if (fastDetermineNameChar(QChar(c)) == NotName) {
1699 putChar(c);
1700 return n;
1701 } else {
1702 ++n;
1703 textBuffer += QChar(c);
1704 }
1705 }
1706
1707 qsizetype pos = textBuffer.size() - n;
1708 putString(textBuffer, pos);
1709 textBuffer.resize(pos);
1710
1711 return n;
1712}
1713
1714void QXmlStreamReaderPrivate::putString(QStringView s, qsizetype from)
1715{
1716 if (from != 0) {
1717 putString(s.mid(from));
1718 return;
1719 }
1720 putStack.reserve(s.size());
1721 for (auto it = s.rbegin(), end = s.rend(); it != end; ++it)
1722 putStack.rawPush() = it->unicode();
1723}
1724
1725void QXmlStreamReaderPrivate::putStringLiteral(QStringView s)
1726{
1727 putStack.reserve(s.size());
1728 for (auto it = s.rbegin(), end = s.rend(); it != end; ++it)
1729 putStack.rawPush() = ((LETTER << 16) | it->unicode());
1730}
1731
1732void QXmlStreamReaderPrivate::putReplacement(QStringView s)
1733{
1734 putStack.reserve(s.size());
1735 for (auto it = s.rbegin(), end = s.rend(); it != end; ++it) {
1736 char16_t c = it->unicode();
1737 if (c == '\n' || c == '\r')
1738 putStack.rawPush() = ((LETTER << 16) | c);
1739 else
1740 putStack.rawPush() = c;
1741 }
1742}
1743void QXmlStreamReaderPrivate::putReplacementInAttributeValue(QStringView s)
1744{
1745 putStack.reserve(s.size());
1746 for (auto it = s.rbegin(), end = s.rend(); it != end; ++it) {
1747 char16_t c = it->unicode();
1748 if (c == '&' || c == ';')
1749 putStack.rawPush() = c;
1750 else if (c == '\n' || c == '\r')
1751 putStack.rawPush() = ' ';
1752 else
1753 putStack.rawPush() = ((LETTER << 16) | c);
1754 }
1755}
1756
1757uint QXmlStreamReaderPrivate::getChar_helper()
1758{
1759 constexpr qsizetype BUFFER_SIZE = 8192;
1760 characterOffset += readBufferPos;
1761 readBufferPos = 0;
1762 if (readBuffer.size())
1763 readBuffer.resize(0);
1764 if (decoder.isValid())
1765 nbytesread = 0;
1766
1767 auto tryDecodeWithGlobalDecoder = [this]() -> bool {
1768 if (!decoder.isValid()) {
1769 // Need 4 bytes: three for BOM (EF BB BF) plus one for the UTF-8 codec
1770 if (nbytesread < 4) {
1771 atEnd = true;
1772 return false;
1773 }
1774 auto encoding = QStringDecoder::encodingForData(rawReadBuffer, u'<');
1775 if (!encoding) // assume utf-8
1776 encoding = QStringDecoder::Utf8;
1777 decoder = QStringDecoder(*encoding);
1778 }
1779
1780 readBuffer = decoder(QByteArrayView(rawReadBuffer).first(nbytesread));
1781
1782 if (lockEncoding && decoder.hasError()) {
1783 readBuffer.clear();
1784 return false;
1785 }
1786
1787 return true;
1788 };
1789
1790 if (device) {
1791 rawReadBuffer.resize(BUFFER_SIZE);
1792 qint64 nbytesreadOrMinus1 = device->read(rawReadBuffer.data() + nbytesread, BUFFER_SIZE - nbytesread);
1793 nbytesread += qMax(nbytesreadOrMinus1, qint64{0});
1794
1795 if (!nbytesread) {
1796 atEnd = true;
1797 return StreamEOF;
1798 }
1799
1800 if (!tryDecodeWithGlobalDecoder())
1801 return StreamEOF;
1802 } else if (dataInfo.empty()) {
1803 atEnd = true;
1804 return StreamEOF;
1805 } else {
1806 const BufferAndEncoding bufAndEnc = dataInfo.takeFirst();
1807
1808 // Use global decoder if the encoding is not set explicitly.
1809 // Here we'll use rawReadBuffer to cache the data from the previous
1810 // chunk with unknown encoding. We need to do it because the size
1811 // of the previous chunk might be too small, and we need to wait
1812 // for more data before we can determine the encoding.
1813 if (bufAndEnc.encoding == QStringDecoder::System) {
1814 if (nbytesread)
1815 rawReadBuffer += bufAndEnc.buffer;
1816 else
1817 rawReadBuffer = bufAndEnc.buffer;
1818 nbytesread = rawReadBuffer.size();
1819
1820 if (!tryDecodeWithGlobalDecoder()) {
1821 // try decoding with the previous chunk decoder
1822 bool hasError = true;
1823 if (chunkDecoder.isValid() && !chunkDecoder.hasError()) {
1824 readBuffer = chunkDecoder(QByteArrayView(rawReadBuffer).first(nbytesread));
1825 hasError = chunkDecoder.hasError();
1826 }
1827 if (hasError) {
1828 raiseWellFormedError(
1829 QXmlStream::tr("Encountered incorrectly encoded content."));
1830 return StreamEOF;
1831 }
1832 }
1833 } else {
1834 if (!isDecoderForEncoding(chunkDecoder, bufAndEnc.encoding))
1835 chunkDecoder = QStringDecoder(bufAndEnc.encoding);
1836 readBuffer = chunkDecoder(bufAndEnc.buffer);
1837 }
1838 }
1839
1840 readBuffer.reserve(1); // keep capacity when calling resize() next time
1841
1842 if (readBufferPos < readBuffer.size()) {
1843 ushort c = readBuffer.at(readBufferPos++).unicode();
1844 return c;
1845 }
1846
1847 atEnd = true;
1848 return StreamEOF;
1849}
1850
1851XmlStringRef QXmlStreamReaderPrivate::namespaceForPrefix(QStringView prefix)
1852{
1853 for (const NamespaceDeclaration &namespaceDeclaration : reversed(namespaceDeclarations)) {
1854 if (namespaceDeclaration.prefix == prefix) {
1855 return namespaceDeclaration.namespaceUri;
1856 }
1857 }
1858
1859#if 1
1860 if (namespaceProcessing && !prefix.isEmpty())
1861 raiseWellFormedError(QXmlStream::tr("Namespace prefix '%1' not declared").arg(prefix));
1862#endif
1863
1864 return XmlStringRef();
1865}
1866
1867struct AttributeName
1868{
1869 QStringView name;
1870 QStringView namespaceUri;
1871
1872 static AttributeName fromXmlAttribute(const QXmlStreamAttribute &a, bool nsProcessing)
1873 {
1874 if (nsProcessing)
1875 return {a.name(), a.namespaceUri()};
1876 else
1877 return {a.qualifiedName(), a.namespaceUri()};
1878 }
1879
1880 friend bool operator==(const AttributeName &lhs, const AttributeName &rhs) noexcept
1881 {
1882 return lhs.name == rhs.name
1883 && lhs.namespaceUri == rhs.namespaceUri;
1884 }
1885 friend size_t qHash(const AttributeName &key, size_t seed = 0) noexcept
1886 {
1887 return qHashMulti(seed,
1888 key.name,
1889 key.namespaceUri);
1890 }
1891};
1892
1893/*
1894 uses namespaceForPrefix and builds the attribute vector
1895 */
1896void QXmlStreamReaderPrivate::resolveTag()
1897{
1898 const auto attributeStackCleaner = qScopeGuard([this](){ attributeStack.clear(); });
1899 const qsizetype n = attributeStack.size();
1900
1901 if (namespaceProcessing) {
1902 for (const DtdAttribute &dtdAttribute : dtdAttributes) {
1903 if (!dtdAttribute.isNamespaceAttribute
1904 || dtdAttribute.defaultValue.isNull()
1905 || dtdAttribute.tagName != qualifiedName
1906 || dtdAttribute.attributeQualifiedName.isNull())
1907 continue;
1908 qsizetype i = 0;
1909 while (i < n && symName(attributeStack[i].key) != dtdAttribute.attributeQualifiedName)
1910 ++i;
1911 if (i != n)
1912 continue;
1913 if (dtdAttribute.attributePrefix.isEmpty() && dtdAttribute.attributeName == "xmlns"_L1) {
1914 NamespaceDeclaration &namespaceDeclaration = namespaceDeclarations.push();
1915 namespaceDeclaration.prefix.clear();
1916
1917 const XmlStringRef ns(dtdAttribute.defaultValue);
1918 if (ns == "http://www.w3.org/2000/xmlns/"_L1 ||
1919 ns == "http://www.w3.org/XML/1998/namespace"_L1)
1920 raiseWellFormedError(QXmlStream::tr("Illegal namespace declaration."));
1921 else
1922 namespaceDeclaration.namespaceUri = ns;
1923 } else if (dtdAttribute.attributePrefix == "xmlns"_L1) {
1924 NamespaceDeclaration &namespaceDeclaration = namespaceDeclarations.push();
1925 XmlStringRef namespacePrefix = dtdAttribute.attributeName;
1926 XmlStringRef namespaceUri = dtdAttribute.defaultValue;
1927 if (((namespacePrefix == "xml"_L1)
1928 ^ (namespaceUri == "http://www.w3.org/XML/1998/namespace"_L1))
1929 || namespaceUri == "http://www.w3.org/2000/xmlns/"_L1
1930 || namespaceUri.isEmpty()
1931 || namespacePrefix == "xmlns"_L1)
1932 raiseWellFormedError(QXmlStream::tr("Illegal namespace declaration."));
1933
1934 namespaceDeclaration.prefix = namespacePrefix;
1935 namespaceDeclaration.namespaceUri = namespaceUri;
1936 }
1937 }
1938 }
1939
1940 tagStack.top().namespaceDeclaration.namespaceUri = namespaceUri = namespaceForPrefix(prefix);
1941
1942 attributes.resize(n);
1943
1944 Q_DECL_UNINITIALIZED
1945 QDuplicateTracker<AttributeName, 13> names(n);
1946
1947 for (qsizetype i = 0; i < n; ++i) {
1948 QXmlStreamAttribute &attribute = attributes[i];
1949 Attribute &attrib = attributeStack[i];
1950 XmlStringRef prefix(symPrefix(attrib.key));
1951 XmlStringRef name(symString(attrib.key));
1952 XmlStringRef qualifiedName(symName(attrib.key));
1953 XmlStringRef value(symString(attrib.value));
1954
1955 attribute.m_name = name;
1956 attribute.m_qualifiedName = qualifiedName;
1957 attribute.m_value = value;
1958
1959 if (!prefix.isEmpty()) {
1960 XmlStringRef attributeNamespaceUri = namespaceForPrefix(prefix);
1961 attribute.m_namespaceUri = XmlStringRef(attributeNamespaceUri);
1962 }
1963
1964 if (names.hasSeen(AttributeName::fromXmlAttribute(attribute, namespaceProcessing))) {
1965 raiseWellFormedError(QXmlStream::tr("Attribute '%1' redefined.").arg(attribute.qualifiedName()));
1966 return;
1967 }
1968 }
1969
1970 for (const DtdAttribute &dtdAttribute : dtdAttributes) {
1971 if (dtdAttribute.isNamespaceAttribute
1972 || dtdAttribute.defaultValue.isNull()
1973 || dtdAttribute.tagName != qualifiedName
1974 || dtdAttribute.attributeQualifiedName.isNull())
1975 continue;
1976 qsizetype i = 0;
1977 while (i < n && symName(attributeStack[i].key) != dtdAttribute.attributeQualifiedName)
1978 ++i;
1979 if (i != n)
1980 continue;
1981
1982
1983
1984 QXmlStreamAttribute attribute;
1985 attribute.m_name = dtdAttribute.attributeName;
1986 attribute.m_qualifiedName = dtdAttribute.attributeQualifiedName;
1987 attribute.m_value = dtdAttribute.defaultValue;
1988
1989 if (!dtdAttribute.attributePrefix.isEmpty()) {
1990 XmlStringRef attributeNamespaceUri = namespaceForPrefix(dtdAttribute.attributePrefix);
1991 attribute.m_namespaceUri = XmlStringRef(attributeNamespaceUri);
1992 }
1993
1994 // Check that the DTD doesn't complement the element's ns1:a with a
1995 // ns2:a where the ns1 and ns2 prefixes resolve to the same
1996 // namespace-URI. This can only happen when namespaceProcessing is on,
1997 // otherwise the prefixes would have matched, and the DTD attribute skipped,
1998 // in the loop over `i` above.
1999
2000 if (namespaceProcessing && names.hasSeen(AttributeName::fromXmlAttribute(attribute, true))) {
2001 raiseWellFormedError(QXmlStream::tr("Attribute '%1' redefined.").arg(attribute.qualifiedName()));
2002 return;
2003 }
2004
2005 attribute.m_isDefault = true;
2006 attributes.append(std::move(attribute));
2007 }
2008}
2009
2010void QXmlStreamReaderPrivate::resolvePublicNamespaces()
2011{
2012 const Tag &tag = tagStack.top();
2013 qsizetype n = namespaceDeclarations.size() - tag.namespaceDeclarationsSize;
2014 publicNamespaceDeclarations.resize(n);
2015 for (qsizetype i = 0; i < n; ++i) {
2016 const NamespaceDeclaration &namespaceDeclaration = namespaceDeclarations.at(tag.namespaceDeclarationsSize + i);
2017 QXmlStreamNamespaceDeclaration &publicNamespaceDeclaration = publicNamespaceDeclarations[i];
2018 publicNamespaceDeclaration.m_prefix = namespaceDeclaration.prefix;
2019 publicNamespaceDeclaration.m_namespaceUri = namespaceDeclaration.namespaceUri;
2020 }
2021}
2022
2023void QXmlStreamReaderPrivate::resolveDtd()
2024{
2025 publicNotationDeclarations.resize(notationDeclarations.size());
2026 for (qsizetype i = 0; i < notationDeclarations.size(); ++i) {
2027 const QXmlStreamReaderPrivate::NotationDeclaration &notationDeclaration = notationDeclarations.at(i);
2028 QXmlStreamNotationDeclaration &publicNotationDeclaration = publicNotationDeclarations[i];
2029 publicNotationDeclaration.m_name = notationDeclaration.name;
2030 publicNotationDeclaration.m_systemId = notationDeclaration.systemId;
2031 publicNotationDeclaration.m_publicId = notationDeclaration.publicId;
2032
2033 }
2034 notationDeclarations.clear();
2035 publicEntityDeclarations.resize(entityDeclarations.size());
2036 for (qsizetype i = 0; i < entityDeclarations.size(); ++i) {
2037 const QXmlStreamReaderPrivate::EntityDeclaration &entityDeclaration = entityDeclarations.at(i);
2038 QXmlStreamEntityDeclaration &publicEntityDeclaration = publicEntityDeclarations[i];
2039 publicEntityDeclaration.m_name = entityDeclaration.name;
2040 publicEntityDeclaration.m_notationName = entityDeclaration.notationName;
2041 publicEntityDeclaration.m_systemId = entityDeclaration.systemId;
2042 publicEntityDeclaration.m_publicId = entityDeclaration.publicId;
2043 publicEntityDeclaration.m_value = entityDeclaration.value;
2044 }
2045 entityDeclarations.clear();
2046 parameterEntityHash.clear();
2047}
2048
2049uint QXmlStreamReaderPrivate::resolveCharRef(int symbolIndex)
2050{
2051 bool ok = true;
2052 uint s;
2053 // ### add toXShort to XmlString?
2054 if (sym(symbolIndex).c == 'x')
2055 s = symString(symbolIndex).view().sliced(1).toUInt(&ok, 16);
2056 else
2057 s = symString(symbolIndex).view().toUInt(&ok, 10);
2058
2059 ok &= (s == 0x9 || s == 0xa || s == 0xd || (s >= 0x20 && s <= 0xd7ff)
2060 || (s >= 0xe000 && s <= 0xfffd) || (s >= 0x10000 && s <= QChar::LastValidCodePoint));
2061
2062 return ok ? s : 0;
2063}
2064
2065
2066void QXmlStreamReaderPrivate::checkPublicLiteral(QStringView publicId)
2067{
2068//#x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]
2069
2070 const char16_t *data = publicId.utf16();
2071 uchar c = 0;
2072 qsizetype i;
2073 for (i = publicId.size() - 1; i >= 0; --i) {
2074 if (data[i] < 256)
2075 switch ((c = data[i])) {
2076 case ' ': case '\n': case '\r': case '-': case '(': case ')':
2077 case '+': case ',': case '.': case '/': case ':': case '=':
2078 case '?': case ';': case '!': case '*': case '#': case '@':
2079 case '$': case '_': case '%': case '\'': case '\"':
2080 continue;
2081 default:
2082 if (isAsciiLetterOrNumber(c))
2083 continue;
2084 }
2085 break;
2086 }
2087 if (i >= 0)
2088 raiseWellFormedError(QXmlStream::tr("Unexpected character '%1' in public id literal.").arg(QChar(QLatin1Char(c))));
2089}
2090
2091/*
2092 Checks whether the document starts with an xml declaration. If it
2093 does, this function returns \c true; otherwise it sets up everything
2094 for a synthetic start document event and returns \c false.
2095 */
2096bool QXmlStreamReaderPrivate::checkStartDocument()
2097{
2098 hasCheckedStartDocument = true;
2099
2100 if (scanString(spell[XML], XML))
2101 return true;
2102
2103 type = QXmlStreamReader::StartDocument;
2104 if (atEnd) {
2105 hasCheckedStartDocument = false;
2106 raiseError(QXmlStreamReader::PrematureEndOfDocumentError);
2107 }
2108 return false;
2109}
2110
2111void QXmlStreamReaderPrivate::startDocument()
2112{
2113 QString err;
2114 if (documentVersion != "1.0"_L1) {
2115 if (documentVersion.view().contains(u' '))
2116 err = QXmlStream::tr("Invalid XML version string.");
2117 else
2118 err = QXmlStream::tr("Unsupported XML version.");
2119 }
2120 qsizetype n = attributeStack.size();
2121
2122 /* We use this bool to ensure that the pesudo attributes are in the
2123 * proper order:
2124 *
2125 * [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>' */
2126
2127 for (qsizetype i = 0; err.isNull() && i < n; ++i) {
2128 Attribute &attrib = attributeStack[i];
2129 XmlStringRef prefix(symPrefix(attrib.key));
2130 XmlStringRef key(symString(attrib.key));
2131 XmlStringRef value(symString(attrib.value));
2132
2133 if (prefix.isEmpty() && key == "encoding"_L1) {
2134 documentEncoding = value;
2135
2136 if (hasStandalone)
2137 err = QXmlStream::tr("The standalone pseudo attribute must appear after the encoding.");
2138 if (!QXmlUtils::isEncName(value))
2139 err = QXmlStream::tr("%1 is an invalid encoding name.").arg(value);
2140 else {
2141 QByteArray enc = value.toString().toUtf8();
2142 if (!lockEncoding) {
2143 decoder = QStringDecoder(enc.constData());
2144 if (!decoder.isValid()) {
2145 // Raise an error only if the data was not already processed
2146 // by the chunk decoder. Otherwise simply fall back to
2147 // UTF-8 for backwards compatibility
2148 if (!chunkDecoder.isValid() || chunkDecoder.hasError())
2149 err = QXmlStream::tr("Encoding %1 is unsupported").arg(value);
2150 else
2151 decoder = QStringDecoder(QStringDecoder::Utf8);
2152 } else if (!rawReadBuffer.isEmpty() && nbytesread) {
2153 // Try to decode with the newly-determined encoding.
2154 // If the decoding is successful, consider it as a
2155 // better match for the decoded data.
2156 // That is only applicable if the previous chunk had
2157 // unspecified (i.e. System) encoding.
2158 QString buf = decoder(QByteArrayView(rawReadBuffer).first(nbytesread));
2159 if (!decoder.hasError())
2160 readBuffer = std::move(buf);
2161 }
2162 }
2163 }
2164 } else if (prefix.isEmpty() && key == "standalone"_L1) {
2165 hasStandalone = true;
2166 if (value == "yes"_L1)
2167 standalone = true;
2168 else if (value == "no"_L1)
2169 standalone = false;
2170 else
2171 err = QXmlStream::tr("Standalone accepts only yes or no.");
2172 } else {
2173 err = QXmlStream::tr("Invalid attribute in XML declaration: %1 = %2").arg(key).arg(value);
2174 }
2175 }
2176
2177 if (!err.isNull())
2178 raiseWellFormedError(err);
2179 attributeStack.clear();
2180}
2181
2182
2183void QXmlStreamReaderPrivate::raiseError(QXmlStreamReader::Error error, const QString& message)
2184{
2185 this->error = error;
2186 errorString = message;
2187 if (errorString.isNull()) {
2188 if (error == QXmlStreamReader::PrematureEndOfDocumentError)
2189 errorString = QXmlStream::tr("Premature end of document.");
2190 else if (error == QXmlStreamReader::CustomError)
2191 errorString = QXmlStream::tr("Invalid document.");
2192 }
2193
2194 type = QXmlStreamReader::Invalid;
2195}
2196
2197void QXmlStreamReaderPrivate::raiseWellFormedError(const QString &message)
2198{
2199 raiseError(QXmlStreamReader::NotWellFormedError, message);
2200}
2201
2202void QXmlStreamReaderPrivate::raiseNamePrefixTooLongError()
2203{
2204 // TODO: add a ImplementationLimitsExceededError and use it instead
2205 raiseError(QXmlStreamReader::NotWellFormedError,
2206 QXmlStream::tr("Length of XML attribute name exceeds implementation limits (4KiB "
2207 "characters)."));
2208}
2209
2210void QXmlStreamReaderPrivate::parseError()
2211{
2212
2213 if (token == EOF_SYMBOL) {
2214 raiseError(QXmlStreamReader::PrematureEndOfDocumentError);
2215 return;
2216 }
2217 const int nmax = 4;
2218 QString error_message;
2219 int ers = state_stack[tos];
2220 int nexpected = 0;
2221 int expected[nmax];
2222 if (token != XML_ERROR)
2223 for (int tk = 0; tk < TERMINAL_COUNT; ++tk) {
2224 int k = t_action(ers, tk);
2225 if (k <= 0)
2226 continue;
2227 if (spell[tk]) {
2228 if (nexpected < nmax)
2229 expected[nexpected++] = tk;
2230 }
2231 }
2232
2233 if (nexpected && nexpected < nmax) {
2234 //: '<first option>'
2235 QString exp_str = QXmlStream::tr("'%1'", "expected")
2236 .arg(QLatin1StringView(spell[expected[0]]));
2237 if (nexpected == 2) {
2238 //: <first option>, '<second option>'
2239 exp_str = QXmlStream::tr("%1 or '%2'", "expected")
2240 .arg(exp_str, QLatin1StringView(spell[expected[1]]));
2241 } else if (nexpected > 2) {
2242 int s = 1;
2243 for (; s < nexpected - 1; ++s) {
2244 //: <options so far>, '<next option>'
2245 exp_str = QXmlStream::tr("%1, '%2'", "expected")
2246 .arg(exp_str, QLatin1StringView(spell[expected[s]]));
2247 }
2248 //: <options so far>, or '<final option>'
2249 exp_str = QXmlStream::tr("%1, or '%2'", "expected")
2250 .arg(exp_str, QLatin1StringView(spell[expected[s]]));
2251 }
2252 error_message = QXmlStream::tr("Expected %1, but got '%2'.")
2253 .arg(exp_str, QLatin1StringView(spell[token]));
2254 } else {
2255 error_message = QXmlStream::tr("Unexpected '%1'.").arg(QLatin1StringView(spell[token]));
2256 }
2257
2258 raiseWellFormedError(error_message);
2259}
2260
2261void QXmlStreamReaderPrivate::resume(int rule) {
2262 resumeReduction = rule;
2263 if (error == QXmlStreamReader::NoError)
2264 raiseError(QXmlStreamReader::PrematureEndOfDocumentError);
2265}
2266
2267/*! Returns the current line number, starting with 1.
2268
2269\sa columnNumber(), characterOffset()
2270 */
2271qint64 QXmlStreamReader::lineNumber() const
2272{
2273 Q_D(const QXmlStreamReader);
2274 return d->lineNumber + 1; // in public we start with 1
2275}
2276
2277/*! Returns the current column number, starting with 0.
2278
2279\sa lineNumber(), characterOffset()
2280 */
2281qint64 QXmlStreamReader::columnNumber() const
2282{
2283 Q_D(const QXmlStreamReader);
2284 return d->characterOffset - d->lastLineStart + d->readBufferPos;
2285}
2286
2287/*! Returns the current character offset, starting with 0.
2288
2289\sa lineNumber(), columnNumber()
2290*/
2291qint64 QXmlStreamReader::characterOffset() const
2292{
2293 Q_D(const QXmlStreamReader);
2294 return d->characterOffset + d->readBufferPos;
2295}
2296
2297
2298/*! Returns the text of \l Characters, \l Comment, \l DTD, or
2299 EntityReference.
2300 */
2301QStringView QXmlStreamReader::text() const
2302{
2303 Q_D(const QXmlStreamReader);
2304 return d->text;
2305}
2306
2307
2308/*! If the tokenType() is \l DTD, this function returns the DTD's
2309 notation declarations. Otherwise an empty vector is returned.
2310
2311 The QXmlStreamNotationDeclarations class is defined to be a QList
2312 of QXmlStreamNotationDeclaration.
2313 */
2314QXmlStreamNotationDeclarations QXmlStreamReader::notationDeclarations() const
2315{
2316 Q_D(const QXmlStreamReader);
2317 if (!d->scanDtd && !d->notationDeclarations.isEmpty())
2318 const_cast<QXmlStreamReaderPrivate *>(d)->resolveDtd();
2319 return d->publicNotationDeclarations;
2320}
2321
2322
2323/*! If the tokenType() is \l DTD, this function returns the DTD's
2324 unparsed (external) entity declarations. Otherwise an empty vector is returned.
2325
2326 The QXmlStreamEntityDeclarations class is defined to be a QList
2327 of QXmlStreamEntityDeclaration.
2328 */
2329QXmlStreamEntityDeclarations QXmlStreamReader::entityDeclarations() const
2330{
2331 Q_D(const QXmlStreamReader);
2332 if (!d->scanDtd && !d->entityDeclarations.isEmpty())
2333 const_cast<QXmlStreamReaderPrivate *>(d)->resolveDtd();
2334 return d->publicEntityDeclarations;
2335}
2336
2337/*!
2338 \since 4.4
2339
2340 If the tokenType() is \l DTD, this function returns the DTD's
2341 name. Otherwise an empty string is returned.
2342
2343 */
2344QStringView QXmlStreamReader::dtdName() const
2345{
2346 Q_D(const QXmlStreamReader);
2347 if (d->type == QXmlStreamReader::DTD)
2348 return d->dtdName;
2349 return QStringView();
2350}
2351
2352/*!
2353 \since 4.4
2354
2355 If the tokenType() is \l DTD, this function returns the DTD's
2356 public identifier. Otherwise an empty string is returned.
2357
2358 */
2359QStringView QXmlStreamReader::dtdPublicId() const
2360{
2361 Q_D(const QXmlStreamReader);
2362 if (d->type == QXmlStreamReader::DTD)
2363 return d->dtdPublicId;
2364 return QStringView();
2365}
2366
2367/*!
2368 \since 4.4
2369
2370 If the tokenType() is \l DTD, this function returns the DTD's
2371 system identifier. Otherwise an empty string is returned.
2372
2373 */
2374QStringView QXmlStreamReader::dtdSystemId() const
2375{
2376 Q_D(const QXmlStreamReader);
2377 if (d->type == QXmlStreamReader::DTD)
2378 return d->dtdSystemId;
2379 return QStringView();
2380}
2381
2382/*!
2383 \since 5.15
2384
2385 Returns the maximum amount of characters a single entity is
2386 allowed to expand into. If a single entity expands past the
2387 given limit, the document is not considered well formed.
2388
2389 \sa setEntityExpansionLimit
2390*/
2391int QXmlStreamReader::entityExpansionLimit() const
2392{
2393 Q_D(const QXmlStreamReader);
2394 return d->entityExpansionLimit;
2395}
2396
2397/*!
2398 \since 5.15
2399
2400 Sets the maximum amount of characters a single entity is
2401 allowed to expand into to \a limit. If a single entity expands
2402 past the given limit, the document is not considered well formed.
2403
2404 The limit is there to prevent DoS attacks when loading unknown
2405 XML documents where recursive entity expansion could otherwise
2406 exhaust all available memory.
2407
2408 The default value for this property is 4096 characters.
2409
2410 The minimum is one (1), to support the built-in XML entities (\c{&lt;} etc).
2411
2412 \sa entityExpansionLimit
2413*/
2414void QXmlStreamReader::setEntityExpansionLimit(int limit)
2415{
2416 Q_D(QXmlStreamReader);
2417 if (limit < 1) {
2418 qWarning("QXmlStreamReader::setEntityExpansionLimit(): "
2419 "limit %d is out of range [1:INT_MAX], clamping to 1.", limit);
2420 }
2421 d->entityExpansionLimit = (std::max)(limit, 1);
2422}
2423
2424/*! If the tokenType() is \l StartElement, this function returns the
2425 element's namespace declarations. Otherwise an empty vector is
2426 returned.
2427
2428 The QXmlStreamNamespaceDeclarations class is defined to be a QList
2429 of QXmlStreamNamespaceDeclaration.
2430
2431 \sa addExtraNamespaceDeclaration(), addExtraNamespaceDeclarations()
2432 */
2433QXmlStreamNamespaceDeclarations QXmlStreamReader::namespaceDeclarations() const
2434{
2435 Q_D(const QXmlStreamReader);
2436 if (d->publicNamespaceDeclarations.isEmpty() && d->type == StartElement)
2437 const_cast<QXmlStreamReaderPrivate *>(d)->resolvePublicNamespaces();
2438 return d->publicNamespaceDeclarations;
2439}
2440
2441
2442/*!
2443 \since 4.4
2444
2445 Adds an \a extraNamespaceDeclaration. The declaration will be
2446 valid for children of the current element, or - should the function
2447 be called before any elements are read - for the entire XML
2448 document.
2449
2450 \sa namespaceDeclarations(), addExtraNamespaceDeclarations(), setNamespaceProcessing()
2451 */
2452void QXmlStreamReader::addExtraNamespaceDeclaration(const QXmlStreamNamespaceDeclaration &extraNamespaceDeclaration)
2453{
2454 Q_D(QXmlStreamReader);
2455 QXmlStreamReaderPrivate::NamespaceDeclaration &namespaceDeclaration = d->namespaceDeclarations.push();
2456 namespaceDeclaration.prefix = d->addToStringStorage(extraNamespaceDeclaration.prefix());
2457 namespaceDeclaration.namespaceUri = d->addToStringStorage(extraNamespaceDeclaration.namespaceUri());
2458}
2459
2460/*!
2461 \since 4.4
2462
2463 Adds a vector of declarations specified by \a extraNamespaceDeclarations.
2464
2465 \sa namespaceDeclarations(), addExtraNamespaceDeclaration()
2466 */
2467void QXmlStreamReader::addExtraNamespaceDeclarations(const QXmlStreamNamespaceDeclarations &extraNamespaceDeclarations)
2468{
2469 for (const auto &extraNamespaceDeclaration : extraNamespaceDeclarations)
2470 addExtraNamespaceDeclaration(extraNamespaceDeclaration);
2471}
2472
2473
2474/*! Convenience function to be called in case a StartElement was
2475 read. Reads until the corresponding EndElement and returns all text
2476 in-between. In case of no error, the current token (see tokenType())
2477 after having called this function is EndElement.
2478
2479 The function concatenates text() when it reads either \l Characters
2480 or EntityReference tokens, but skips ProcessingInstruction and \l
2481 Comment. If the current token is not StartElement, an empty string is
2482 returned.
2483
2484 The \a behaviour defines what happens in case anything else is
2485 read before reaching EndElement. The function can include the text from
2486 child elements (useful for example for HTML), ignore child elements, or
2487 raise an UnexpectedElementError and return what was read so far (default).
2488
2489 \since 4.6
2490 */
2491QString QXmlStreamReader::readElementText(ReadElementTextBehaviour behaviour)
2492{
2493 Q_D(QXmlStreamReader);
2494 if (isStartElement()) {
2495 QString result;
2496 qsizetype nestingLevel = 1;
2497 do {
2498 switch (readNext()) {
2499 case Characters:
2500 case EntityReference:
2501 result.insert(result.size(), d->text);
2502 break;
2503 case EndElement:
2504 --nestingLevel;
2505 break;
2506 case ProcessingInstruction:
2507 case Comment:
2508 break;
2509 case StartElement:
2510 if (behaviour == SkipChildElements) {
2511 skipCurrentElement();
2512 break;
2513 } else if (behaviour == IncludeChildElements) {
2514 ++nestingLevel;
2515 break;
2516 }
2517 Q_FALLTHROUGH();
2518 default:
2519 if (d->error || behaviour == ErrorOnUnexpectedElement) {
2520 if (!d->error)
2521 d->raiseError(UnexpectedElementError, QXmlStream::tr("Expected character data."));
2522 return result;
2523 }
2524 }
2525 } while (nestingLevel);
2526 return result;
2527 }
2528 return QString();
2529}
2530
2531/*! Raises a custom error with an optional error \a message.
2532
2533 \sa error(), errorString()
2534 */
2535void QXmlStreamReader::raiseError(const QString& message)
2536{
2537 Q_D(QXmlStreamReader);
2538 d->raiseError(CustomError, message);
2539}
2540
2541/*!
2542 Returns the error message that was set with raiseError().
2543
2544 \sa error(), lineNumber(), columnNumber(), characterOffset()
2545 */
2546QString QXmlStreamReader::errorString() const
2547{
2548 Q_D(const QXmlStreamReader);
2549 if (d->type == QXmlStreamReader::Invalid)
2550 return d->errorString;
2551 return QString();
2552}
2553
2554/*! Returns the type of the current error, or NoError if no error occurred.
2555
2556 \sa errorString(), raiseError()
2557 */
2558QXmlStreamReader::Error QXmlStreamReader::error() const
2559{
2560 Q_D(const QXmlStreamReader);
2561 if (d->type == QXmlStreamReader::Invalid)
2562 return d->error;
2563 return NoError;
2564}
2565
2566/*!
2567 Returns the target of a ProcessingInstruction.
2568 */
2569QStringView QXmlStreamReader::processingInstructionTarget() const
2570{
2571 Q_D(const QXmlStreamReader);
2572 return d->processingInstructionTarget;
2573}
2574
2575/*!
2576 Returns the data of a ProcessingInstruction.
2577 */
2578QStringView QXmlStreamReader::processingInstructionData() const
2579{
2580 Q_D(const QXmlStreamReader);
2581 return d->processingInstructionData;
2582}
2583
2584
2585
2586/*!
2587 Returns the local name of a StartElement, EndElement, or an EntityReference.
2588
2589 \sa namespaceUri(), qualifiedName()
2590 */
2591QStringView QXmlStreamReader::name() const
2592{
2593 Q_D(const QXmlStreamReader);
2594 return d->name;
2595}
2596
2597/*!
2598 Returns the namespaceUri of a StartElement or EndElement.
2599
2600 \sa name(), qualifiedName()
2601 */
2602QStringView QXmlStreamReader::namespaceUri() const
2603{
2604 Q_D(const QXmlStreamReader);
2605 return d->namespaceUri;
2606}
2607
2608/*!
2609 Returns the qualified name of a StartElement or EndElement;
2610
2611 A qualified name is the raw name of an element in the XML data. It
2612 consists of the namespace prefix, followed by colon, followed by the
2613 element's local name. Since the namespace prefix is not unique (the
2614 same prefix can point to different namespaces and different prefixes
2615 can point to the same namespace), you shouldn't use qualifiedName(),
2616 but the resolved namespaceUri() and the attribute's local name().
2617
2618 \sa name(), prefix(), namespaceUri()
2619 */
2620QStringView QXmlStreamReader::qualifiedName() const
2621{
2622 Q_D(const QXmlStreamReader);
2623 return d->qualifiedName;
2624}
2625
2626
2627
2628/*!
2629 \since 4.4
2630
2631 Returns the prefix of a StartElement or EndElement.
2632
2633 \sa name(), qualifiedName()
2634*/
2635QStringView QXmlStreamReader::prefix() const
2636{
2637 Q_D(const QXmlStreamReader);
2638 return d->prefix;
2639}
2640
2641/*!
2642 Returns the attributes of a StartElement.
2643 */
2644QXmlStreamAttributes QXmlStreamReader::attributes() const
2645{
2646 Q_D(const QXmlStreamReader);
2647 return d->attributes;
2648}
2649
2650#endif // feature xmlstreamreader
2651
2652/*!
2653 \class QXmlStreamAttribute
2654 \inmodule QtCore
2655 \since 4.3
2656 \reentrant
2657 \brief The QXmlStreamAttribute class represents a single XML attribute.
2658
2659 \ingroup xml-tools
2660
2661 \compares equality
2662
2663 An attribute consists of an optionally empty namespaceUri(), a
2664 name(), a value(), and an isDefault() attribute.
2665
2666 The raw XML attribute name is returned as qualifiedName().
2667*/
2668
2669/*!
2670 Creates an empty attribute.
2671 */
2672QXmlStreamAttribute::QXmlStreamAttribute()
2673{
2674 m_isDefault = false;
2675}
2676
2677/*! Constructs an attribute in the namespace described with \a
2678 namespaceUri with \a name and value \a value.
2679
2680 The attribute will have isDefault() == \c{false}.
2681 */
2682QXmlStreamAttribute::QXmlStreamAttribute(const QString &namespaceUri, const QString &name, const QString &value)
2683 : m_isDefault(false)
2684{
2685 m_namespaceUri = namespaceUri;
2686 m_name = m_qualifiedName = name;
2687 m_value = value;
2688}
2689
2690/*!
2691 Constructs an attribute with qualified name \a qualifiedName and value \a value.
2692
2693 The attribute will have isDefault() == \c{false}.
2694 */
2695QXmlStreamAttribute::QXmlStreamAttribute(const QString &qualifiedName, const QString &value)
2696 : m_isDefault(false)
2697{
2698 qsizetype colon = qualifiedName.indexOf(u':');
2699 m_name = qualifiedName.mid(colon + 1);
2700 m_qualifiedName = qualifiedName;
2701 m_value = value;
2702}
2703
2704/*! \fn QStringView QXmlStreamAttribute::namespaceUri() const
2705
2706 Returns the attribute's resolved namespaceUri, or an empty string
2707 reference if the attribute does not have a defined namespace.
2708 */
2709/*! \fn QStringView QXmlStreamAttribute::name() const
2710 Returns the attribute's local name.
2711 */
2712/*! \fn QStringView QXmlStreamAttribute::qualifiedName() const
2713 Returns the attribute's qualified name.
2714
2715 A qualified name is the raw name of an attribute in the XML
2716 data. It consists of the namespace prefix(), followed by colon,
2717 followed by the attribute's local name(). Since the namespace prefix
2718 is not unique (the same prefix can point to different namespaces
2719 and different prefixes can point to the same namespace), you
2720 shouldn't use qualifiedName(), but the resolved namespaceUri() and
2721 the attribute's local name().
2722 */
2723/*!
2724 \fn QStringView QXmlStreamAttribute::prefix() const
2725 \since 4.4
2726 Returns the attribute's namespace prefix.
2727
2728 \sa name(), qualifiedName()
2729
2730*/
2731
2732/*! \fn QStringView QXmlStreamAttribute::value() const
2733 Returns the attribute's value.
2734 */
2735
2736/*! \fn bool QXmlStreamAttribute::isDefault() const
2737
2738 Returns \c true if the parser added this attribute with a default
2739 value following an ATTLIST declaration in the DTD; otherwise
2740 returns \c false.
2741*/
2742/*! \fn bool QXmlStreamAttribute::operator==(const QXmlStreamAttribute &lhs, const QXmlStreamAttribute &rhs)
2743
2744 Compares \a lhs attribute with \a rhs and returns \c true if they are
2745 equal; otherwise returns \c false.
2746 */
2747/*! \fn bool QXmlStreamAttribute::operator!=(const QXmlStreamAttribute &lhs, const QXmlStreamAttribute &rhs)
2748
2749 Compares \a lhs attribute with \a rhs and returns \c true if they are
2750 not equal; otherwise returns \c false.
2751 */
2752
2753/*!
2754 \class QXmlStreamAttributes
2755 \inmodule QtCore
2756 \since 4.3
2757 \reentrant
2758 \brief The QXmlStreamAttributes class represents a vector of QXmlStreamAttribute.
2759
2760 Attributes are returned by a QXmlStreamReader in
2761 \l{QXmlStreamReader::attributes()} {attributes()} when the reader
2762 reports a \l {QXmlStreamReader::StartElement}{start element}. The
2763 class can also be used with a QXmlStreamWriter as an argument to
2764 \l {QXmlStreamWriter::writeAttributes()}{writeAttributes()}.
2765
2766 The convenience function value() loops over the vector and returns
2767 an attribute value for a given namespaceUri and an attribute's
2768 name.
2769
2770 New attributes can be added with append().
2771
2772 \ingroup xml-tools
2773*/
2774
2775/*!
2776 \fn QXmlStreamAttributes::QXmlStreamAttributes()
2777
2778 A constructor for QXmlStreamAttributes.
2779*/
2780
2781/*!
2782 \typedef QXmlStreamNotationDeclarations
2783 \relates QXmlStreamNotationDeclaration
2784
2785 Synonym for QList<QXmlStreamNotationDeclaration>.
2786*/
2787
2788
2789/*!
2790 \class QXmlStreamNotationDeclaration
2791 \inmodule QtCore
2792 \since 4.3
2793 \reentrant
2794 \brief The QXmlStreamNotationDeclaration class represents a DTD notation declaration.
2795
2796 \ingroup xml-tools
2797
2798 \compares equality
2799
2800 An notation declaration consists of a name(), a systemId(), and a publicId().
2801*/
2802
2803/*!
2804 Creates an empty notation declaration.
2805*/
2806QXmlStreamNotationDeclaration::QXmlStreamNotationDeclaration()
2807{
2808}
2809
2810/*! \fn QStringView QXmlStreamNotationDeclaration::name() const
2811
2812Returns the notation name.
2813*/
2814/*! \fn QStringView QXmlStreamNotationDeclaration::systemId() const
2815
2816Returns the system identifier.
2817*/
2818/*! \fn QStringView QXmlStreamNotationDeclaration::publicId() const
2819
2820Returns the public identifier.
2821*/
2822
2823/*! \fn inline bool QXmlStreamNotationDeclaration::operator==(const QXmlStreamNotationDeclaration &lhs, const QXmlStreamNotationDeclaration &rhs)
2824
2825 Compares \a lhs notation declaration with \a rhs and returns \c true
2826 if they are equal; otherwise returns \c false.
2827 */
2828/*! \fn inline bool QXmlStreamNotationDeclaration::operator!=(const QXmlStreamNotationDeclaration &lhs, const QXmlStreamNotationDeclaration &rhs)
2829
2830 Compares \a lhs notation declaration with \a rhs and returns \c true
2831 if they are not equal; otherwise returns \c false.
2832 */
2833
2834/*!
2835 \typedef QXmlStreamNamespaceDeclarations
2836 \relates QXmlStreamNamespaceDeclaration
2837
2838 Synonym for QList<QXmlStreamNamespaceDeclaration>.
2839*/
2840
2841/*!
2842 \class QXmlStreamNamespaceDeclaration
2843 \inmodule QtCore
2844 \since 4.3
2845 \reentrant
2846 \brief The QXmlStreamNamespaceDeclaration class represents a namespace declaration.
2847
2848 \ingroup xml-tools
2849
2850 \compares equality
2851
2852 An namespace declaration consists of a prefix() and a namespaceUri().
2853*/
2854/*! \fn inline bool QXmlStreamNamespaceDeclaration::operator==(const QXmlStreamNamespaceDeclaration &lhs, const QXmlStreamNamespaceDeclaration &rhs)
2855
2856 Compares \a lhs namespace declaration with \a rhs and returns \c true
2857 if they are equal; otherwise returns \c false.
2858 */
2859/*! \fn inline bool QXmlStreamNamespaceDeclaration::operator!=(const QXmlStreamNamespaceDeclaration &lhs, const QXmlStreamNamespaceDeclaration &rhs)
2860
2861 Compares \a lhs namespace declaration with \a rhs and returns \c true
2862 if they are not equal; otherwise returns \c false.
2863 */
2864
2865/*!
2866 Creates an empty namespace declaration.
2867*/
2868QXmlStreamNamespaceDeclaration::QXmlStreamNamespaceDeclaration()
2869{
2870}
2871
2872/*!
2873 \since 4.4
2874
2875 Creates a namespace declaration with \a prefix and \a namespaceUri.
2876*/
2877QXmlStreamNamespaceDeclaration::QXmlStreamNamespaceDeclaration(const QString &prefix, const QString &namespaceUri)
2878{
2879 m_prefix = prefix;
2880 m_namespaceUri = namespaceUri;
2881}
2882
2883/*! \fn QStringView QXmlStreamNamespaceDeclaration::prefix() const
2884
2885Returns the prefix.
2886*/
2887/*! \fn QStringView QXmlStreamNamespaceDeclaration::namespaceUri() const
2888
2889Returns the namespaceUri.
2890*/
2891
2892
2893
2894
2895/*!
2896 \typedef QXmlStreamEntityDeclarations
2897 \relates QXmlStreamEntityDeclaration
2898
2899 Synonym for QList<QXmlStreamEntityDeclaration>.
2900*/
2901
2902/*!
2903 \class QXmlString
2904 \inmodule QtCore
2905 \since 6.0
2906 \internal
2907*/
2908
2909/*!
2910 \class QXmlStreamEntityDeclaration
2911 \inmodule QtCore
2912 \since 4.3
2913 \reentrant
2914 \brief The QXmlStreamEntityDeclaration class represents a DTD entity declaration.
2915
2916 \ingroup xml-tools
2917
2918 \compares equality
2919 An entity declaration consists of a name(), a notationName(), a
2920 systemId(), a publicId(), and a value().
2921*/
2922
2923/*!
2924 Creates an empty entity declaration.
2925*/
2926QXmlStreamEntityDeclaration::QXmlStreamEntityDeclaration()
2927{
2928}
2929
2930/*! \fn QStringView QXmlStreamEntityDeclaration::name() const
2931
2932Returns the entity name.
2933*/
2934/*! \fn QStringView QXmlStreamEntityDeclaration::notationName() const
2935
2936Returns the notation name.
2937*/
2938/*! \fn QStringView QXmlStreamEntityDeclaration::systemId() const
2939
2940Returns the system identifier.
2941*/
2942/*! \fn QStringView QXmlStreamEntityDeclaration::publicId() const
2943
2944Returns the public identifier.
2945*/
2946/*! \fn QStringView QXmlStreamEntityDeclaration::value() const
2947
2948Returns the entity's value.
2949*/
2950
2951/*! \fn bool QXmlStreamEntityDeclaration::operator==(const QXmlStreamEntityDeclaration &lhs, const QXmlStreamEntityDeclaration &rhs)
2952
2953 Compares \a lhs entity declaration with \a rhs and returns \c true if
2954 they are equal; otherwise returns \c false.
2955 */
2956/*! \fn bool QXmlStreamEntityDeclaration::operator!=(const QXmlStreamEntityDeclaration &lhs, const QXmlStreamEntityDeclaration &rhs)
2957
2958 Compares \a lhs entity declaration with \a rhs and returns \c true if
2959 they are not equal; otherwise returns \c false.
2960 */
2961
2962/*! Returns the value of the attribute \a name in the namespace
2963 described with \a namespaceUri, or an empty string reference if the
2964 attribute is not defined. The \a namespaceUri can be empty.
2965
2966 \note In Qt versions prior to 6.6, this function was implemented as an
2967 overload set accepting combinations of QString and QLatin1StringView only.
2968 */
2969QStringView QXmlStreamAttributes::value(QAnyStringView namespaceUri, QAnyStringView name) const noexcept
2970{
2971 for (const QXmlStreamAttribute &attribute : *this) {
2972 if (attribute.name() == name && attribute.namespaceUri() == namespaceUri)
2973 return attribute.value();
2974 }
2975 return QStringView();
2976}
2977
2978/*!\overload
2979
2980 Returns the value of the attribute with qualified name \a
2981 qualifiedName , or an empty string reference if the attribute is not
2982 defined. A qualified name is the raw name of an attribute in the XML
2983 data. It consists of the namespace prefix, followed by colon,
2984 followed by the attribute's local name. Since the namespace prefix
2985 is not unique (the same prefix can point to different namespaces and
2986 different prefixes can point to the same namespace), you shouldn't
2987 use qualified names, but a resolved namespaceUri and the attribute's
2988 local name.
2989
2990 \note In Qt versions prior to 6.6, this function was implemented as an
2991 overload set accepting QString and QLatin1StringView only.
2992
2993 */
2994QStringView QXmlStreamAttributes::value(QAnyStringView qualifiedName) const noexcept
2995{
2996 for (const QXmlStreamAttribute &attribute : *this) {
2997 if (attribute.qualifiedName() == qualifiedName)
2998 return attribute.value();
2999 }
3000 return QStringView();
3001}
3002
3003/*!Appends a new attribute with \a name in the namespace
3004 described with \a namespaceUri, and value \a value. The \a
3005 namespaceUri can be empty.
3006 */
3007void QXmlStreamAttributes::append(const QString &namespaceUri, const QString &name, const QString &value)
3008{
3009 append(QXmlStreamAttribute(namespaceUri, name, value));
3010}
3011
3012/*!\overload
3013 Appends a new attribute with qualified name \a qualifiedName and
3014 value \a value.
3015 */
3016void QXmlStreamAttributes::append(const QString &qualifiedName, const QString &value)
3017{
3018 append(QXmlStreamAttribute(qualifiedName, value));
3019}
3020
3021#if QT_CONFIG(xmlstreamreader)
3022
3023/*! \fn bool QXmlStreamReader::isStartDocument() const
3024 Returns \c true if tokenType() equals \l StartDocument; otherwise returns \c false.
3025*/
3026/*! \fn bool QXmlStreamReader::isEndDocument() const
3027 Returns \c true if tokenType() equals \l EndDocument; otherwise returns \c false.
3028*/
3029/*! \fn bool QXmlStreamReader::isStartElement() const
3030 Returns \c true if tokenType() equals \l StartElement; otherwise returns \c false.
3031*/
3032/*! \fn bool QXmlStreamReader::isEndElement() const
3033 Returns \c true if tokenType() equals \l EndElement; otherwise returns \c false.
3034*/
3035/*! \fn bool QXmlStreamReader::isCharacters() const
3036 Returns \c true if tokenType() equals \l Characters; otherwise returns \c false.
3037
3038 \sa isWhitespace(), isCDATA()
3039*/
3040/*! \fn bool QXmlStreamReader::isComment() const
3041 Returns \c true if tokenType() equals \l Comment; otherwise returns \c false.
3042*/
3043/*! \fn bool QXmlStreamReader::isDTD() const
3044 Returns \c true if tokenType() equals \l DTD; otherwise returns \c false.
3045*/
3046/*! \fn bool QXmlStreamReader::isEntityReference() const
3047 Returns \c true if tokenType() equals \l EntityReference; otherwise returns \c false.
3048*/
3049/*! \fn bool QXmlStreamReader::isProcessingInstruction() const
3050 Returns \c true if tokenType() equals \l ProcessingInstruction; otherwise returns \c false.
3051*/
3052
3053/*! Returns \c true if the reader reports characters that only consist
3054 of white-space; otherwise returns \c false.
3055
3056 \sa isCharacters(), text()
3057*/
3058bool QXmlStreamReader::isWhitespace() const
3059{
3060 Q_D(const QXmlStreamReader);
3061 return d->type == QXmlStreamReader::Characters && d->isWhitespace;
3062}
3063
3064/*! Returns \c true if the reader reports characters that stem from a
3065 CDATA section; otherwise returns \c false.
3066
3067 \sa isCharacters(), text()
3068*/
3069bool QXmlStreamReader::isCDATA() const
3070{
3071 Q_D(const QXmlStreamReader);
3072 return d->type == QXmlStreamReader::Characters && d->isCDATA;
3073}
3074
3075
3076
3077/*!
3078 Returns \c true if this document has been declared standalone in the
3079 XML declaration; otherwise returns \c false.
3080
3081 If no XML declaration has been parsed, this function returns \c false.
3082
3083 \sa hasStandaloneDeclaration()
3084 */
3085bool QXmlStreamReader::isStandaloneDocument() const
3086{
3087 Q_D(const QXmlStreamReader);
3088 return d->standalone;
3089}
3090
3091/*!
3092 \since 6.6
3093
3094 Returns \c true if this document has an explicit standalone
3095 declaration (can be 'yes' or 'no'); otherwise returns \c false;
3096
3097 If no XML declaration has been parsed, this function returns \c false.
3098
3099 \sa isStandaloneDocument()
3100 */
3101bool QXmlStreamReader::hasStandaloneDeclaration() const
3102{
3103 Q_D(const QXmlStreamReader);
3104 return d->hasStandalone;
3105}
3106
3107/*!
3108 \since 4.4
3109
3110 If the tokenType() is \l StartDocument, this function returns the
3111 version string as specified in the XML declaration.
3112 Otherwise an empty string is returned.
3113 */
3114QStringView QXmlStreamReader::documentVersion() const
3115{
3116 Q_D(const QXmlStreamReader);
3117 if (d->type == QXmlStreamReader::StartDocument)
3118 return d->documentVersion;
3119 return QStringView();
3120}
3121
3122/*!
3123 \since 4.4
3124
3125 If the tokenType() is \l StartDocument, this function returns the
3126 encoding string as specified in the XML declaration.
3127 Otherwise an empty string is returned.
3128 */
3129QStringView QXmlStreamReader::documentEncoding() const
3130{
3131 Q_D(const QXmlStreamReader);
3132 if (d->type == QXmlStreamReader::StartDocument)
3133 return d->documentEncoding;
3134 return QStringView();
3135}
3136
3137#endif // feature xmlstreamreader
3138
3139/*!
3140 \class QXmlStreamWriter
3141 \inmodule QtCore
3142 \since 4.3
3143 \reentrant
3144
3145 \brief The QXmlStreamWriter class provides an XML 1.0 writer with a
3146 simple streaming API.
3147
3148 \ingroup xml-tools
3149 \ingroup qtserialization
3150
3151 QXmlStreamWriter is the counterpart to QXmlStreamReader for writing
3152 XML.
3153 It is compliant with the XML 1.0 specification and writes documents
3154 using XML 1.0 syntax, escaping rules, and character validity
3155 constraints.
3156 \note XML 1.1 is not supported. While version strings may be set
3157 manually in the output, documents requiring features specific to
3158 XML 1.1, such as additional control characters cannot be produced
3159 using this class.
3160
3161 Like its related class, it operates on a QIODevice specified
3162 with setDevice(). The API is simple and straightforward: for every
3163 XML token or event you want to write, the writer provides a
3164 specialized function.
3165
3166 You start a document with writeStartDocument() and end it with
3167 writeEndDocument(). This will implicitly close all remaining open
3168 tags.
3169
3170 Element tags are opened with writeStartElement() followed by
3171 writeAttribute() or writeAttributes(), element content, and then
3172 writeEndElement(). A shorter form writeEmptyElement() can be used
3173 to write empty elements, followed by writeAttributes().
3174
3175 Element content consists of either characters, entity references or
3176 nested elements. It is written with writeCharacters(), which also
3177 takes care of escaping all forbidden characters and character
3178 sequences, writeEntityReference(), or subsequent calls to
3179 writeStartElement(). A convenience method writeTextElement() can be
3180 used for writing terminal elements that contain nothing but text.
3181
3182 The following abridged code snippet shows the basic use of the class
3183 to write formatted XML with indentation:
3184
3185 \snippet qxmlstreamwriter/main.cpp start stream
3186 \dots
3187 \snippet qxmlstreamwriter/main.cpp write element
3188 \dots
3189 \snippet qxmlstreamwriter/main.cpp finish stream
3190
3191 QXmlStreamWriter takes care of prefixing namespaces, all you have to
3192 do is specify the \c namespaceUri when writing elements or
3193 attributes. If you must conform to certain prefixes, you can force
3194 the writer to use them by declaring the namespaces manually with
3195 either writeNamespace() or writeDefaultNamespace(). Alternatively,
3196 you can bypass the stream writer's namespace support and use
3197 overloaded methods that take a qualified name instead. The namespace
3198 \e http://www.w3.org/XML/1998/namespace is implicit and mapped to the
3199 prefix \e xml.
3200
3201 The stream writer can automatically format the generated XML data by
3202 adding line-breaks and indentation to empty sections between
3203 elements, making the XML data more readable for humans and easier to
3204 work with for most source code management systems. The feature can
3205 be turned on with the \l autoFormatting property, and customized
3206 with the \l autoFormattingIndent property.
3207
3208 Other functions are writeCDATA(), writeComment(),
3209 writeProcessingInstruction(), and writeDTD(). Chaining of XML
3210 streams is supported with writeCurrentToken().
3211
3212 QXmlStreamWriter always encodes XML in UTF-8.
3213
3214 If an error occurs while writing, \l hasError() will return true.
3215 However, by default, data that was already buffered at the time the error
3216 occurred, or data written from within the same operation, may still be
3217 written to the underlying device. This applies to \l Error::Encoding,
3218 \l Error::InvalidCharacter, and user-raised \l Error::Custom.
3219 To avoid this and ensure no data is written after an error, use the
3220 \l stopWritingOnError property. When this property is enabled,
3221 the first error stops output immediately and the writer ignores all
3222 subsequent write operations.
3223 Applications should treat the error state as terminal and avoid further
3224 use of the writer after an error.
3225
3226 The \l{QXmlStream Bookmarks Example} illustrates how to use a
3227 stream writer to write an XML bookmark file (XBEL) that
3228 was previously read in by a QXmlStreamReader.
3229
3230*/
3231
3232/*!
3233 \enum QXmlStreamWriter::Error
3234
3235 This enum specifies the different error cases that can occur
3236 when writing XML with QXmlStreamWriter.
3237
3238 \value None No error has occurred.
3239
3240 \value IO An I/O error occurred while writing to the
3241 device.
3242
3243 \value Encoding An encoding error occurred while converting
3244 characters to the output format.
3245
3246 \value InvalidCharacter A character not permitted in XML 1.0
3247 was encountered while writing.
3248
3249 \value Custom A custom error has been raised with
3250 \l raiseError().
3251
3252 \since 6.10
3253*/
3254
3255#if QT_CONFIG(xmlstreamwriter)
3256
3257class QXmlStreamWriterPrivate : public QXmlStreamPrivateTagStack
3258{
3259 QXmlStreamWriter *q_ptr;
3260 Q_DECLARE_PUBLIC(QXmlStreamWriter)
3261public:
3262 enum class StartElementOption {
3263 KeepEverything = 0, // write out every attribute, namespace, &c.
3264 OmitNamespaceDeclarations = 1,
3265 };
3266
3267 QXmlStreamWriterPrivate(QXmlStreamWriter *q);
3268 ~QXmlStreamWriterPrivate() {
3269 if (deleteDevice)
3270 delete device;
3271 }
3272
3273 void raiseError(QXmlStreamWriter::Error error);
3274 void raiseError(QXmlStreamWriter::Error error, QAnyStringView message);
3275 void write(QAnyStringView s);
3276 void writeEscaped(QAnyStringView, bool escapeWhitespace = false);
3277 bool finishStartElement(bool contents = true);
3278 void writeStartElement(QAnyStringView namespaceUri, QAnyStringView name,
3279 StartElementOption option = StartElementOption::KeepEverything);
3280 QIODevice *device = nullptr;
3281 QString *stringDevice = nullptr;
3282 uint deleteDevice :1;
3283 uint inStartElement :1;
3284 uint inEmptyElement :1;
3285 uint lastWasStartElement :1;
3286 uint wroteSomething :1;
3287 uint autoFormatting :1;
3288 uint didWriteStartDocument :1;
3289 uint didWriteAnyToken :1;
3290 uint stopWritingOnError :1;
3291 std::string autoFormattingIndent = std::string(4, ' ');
3292 NamespaceDeclaration emptyNamespace;
3293 qsizetype lastNamespaceDeclaration = 1;
3294 QXmlStreamWriter::Error error = QXmlStreamWriter::Error::None;
3295 QString errorString;
3296
3297 NamespaceDeclaration &addExtraNamespace(QAnyStringView namespaceUri, QAnyStringView prefix);
3298 NamespaceDeclaration &findNamespace(QAnyStringView namespaceUri, bool writeDeclaration = false, bool noDefault = false);
3299 void writeNamespaceDeclaration(const NamespaceDeclaration &namespaceDeclaration);
3300
3301 int namespacePrefixCount = 0;
3302
3303 void indent(int level);
3304private:
3305 void doWriteToDevice(QStringView s);
3306 void doWriteToDevice(QUtf8StringView s);
3307 void doWriteToDevice(QLatin1StringView s);
3308};
3309
3310
3311QXmlStreamWriterPrivate::QXmlStreamWriterPrivate(QXmlStreamWriter *q)
3312 : q_ptr(q), deleteDevice(false), inStartElement(false),
3313 inEmptyElement(false), lastWasStartElement(false),
3314 wroteSomething(false), autoFormatting(false),
3315 didWriteStartDocument(false), didWriteAnyToken(false),
3316 stopWritingOnError(false)
3317{
3318}
3319
3320void QXmlStreamWriterPrivate::raiseError(QXmlStreamWriter::Error errorCode)
3321{
3322 error = errorCode;
3323 switch (error) {
3324 case QXmlStreamWriter::Error::IO:
3325 errorString = QXmlStream::tr("An I/O error occurred while writing");
3326 break;
3327 case QXmlStreamWriter::Error::Encoding:
3328 errorString = QXmlStream::tr("An encoding error occurred while writing");
3329 break;
3330 case QXmlStreamWriter::Error::InvalidCharacter:
3331 errorString = QXmlStream::tr("Encountered an invalid XML 1.0 character while writing");
3332 break;
3333 case QXmlStreamWriter::Error::Custom:
3334 errorString = QXmlStream::tr("An error occurred while writing");
3335 break;
3336 case QXmlStreamWriter::Error::None:
3337 errorString.clear();
3338 break;
3339 }
3340}
3341
3342void QXmlStreamWriterPrivate::raiseError(QXmlStreamWriter::Error errorCode, QAnyStringView message)
3343{
3344 error = errorCode;
3345 errorString = message.toString();
3346}
3347
3348void QXmlStreamWriterPrivate::write(QAnyStringView s)
3349{
3350 if (stopWritingOnError && (error != QXmlStreamWriter::Error::None))
3351 return;
3352 if (device) {
3353 if (error == QXmlStreamWriter::Error::IO)
3354 return;
3355
3356 s.visit([&] (auto s) { doWriteToDevice(s); });
3357 } else if (stringDevice) {
3358 s.visit([&] (auto s) { stringDevice->append(s); });
3359 } else {
3360 qWarning("QXmlStreamWriter: No device");
3361 }
3362}
3363
3364void QXmlStreamWriterPrivate::writeEscaped(QAnyStringView s, bool escapeWhitespace)
3365{
3366 struct NextResult {
3367 char32_t value;
3368 bool encodingError;
3369 };
3370 struct NextLatin1 {
3371 NextResult operator()(const char *&it, const char *) const
3372 { return {uchar(*it++), false}; }
3373 };
3374 struct NextUtf8 {
3375 NextResult operator()(const char *&it, const char *end) const
3376 {
3377 // We can have '\0' in the text, and it should be reported as
3378 // Error::InvalidCharacter, not as Error::Encoding
3379 constexpr char32_t invalidValue = 0xFFFFFFFF;
3380 static_assert(invalidValue > QChar::LastValidCodePoint);
3381 auto i = reinterpret_cast<const qchar8_t *>(it);
3382 const auto old_i = i;
3383 const auto e = reinterpret_cast<const qchar8_t *>(end);
3384 const char32_t result = QUtf8Functions::nextUcs4FromUtf8(i, e, invalidValue);
3385 it += i - old_i;
3386 return result == invalidValue ? NextResult{U'\0', true}
3387 : NextResult{result, false};
3388 }
3389 };
3390 struct NextUtf16 {
3391 NextResult operator()(const QChar *&it, const QChar *end) const
3392 {
3393 QStringIterator decoder(it, end);
3394 // We can have '\0' in the text, and it should be reported as
3395 // Error::InvalidCharacter, not as Error::Encoding
3396 constexpr char32_t invalidValue = 0xFFFFFFFF;
3397 static_assert(invalidValue > QChar::LastValidCodePoint);
3398 char32_t result = decoder.next(invalidValue);
3399 it = decoder.position();
3400 return result == invalidValue ? NextResult{U'\0', true}
3401 : NextResult{result, false};
3402 }
3403 };
3404
3405 QString escaped;
3406 escaped.reserve(s.size());
3407 s.visit([&] (auto s) {
3408 using View = decltype(s);
3409 using Decoder = std::conditional_t<std::is_same_v<View, QLatin1StringView>, NextLatin1,
3410 std::conditional_t<std::is_same_v<View, QUtf8StringView>, NextUtf8, NextUtf16>>;
3411
3412 auto it = s.begin();
3413 const auto end = s.end();
3414 Decoder decoder;
3415
3416 while (it != end) {
3417 QLatin1StringView replacement;
3418 auto mark = it;
3419
3420 while (it != end) {
3421 auto next_it = it;
3422 const auto decoded = decoder(next_it, end);
3423 switch (decoded.value) {
3424 case u'<':
3425 replacement = "&lt;"_L1;
3426 break;
3427 case u'>':
3428 replacement = "&gt;"_L1;
3429 break;
3430 case u'&':
3431 replacement = "&amp;"_L1;
3432 break;
3433 case u'\"':
3434 replacement = "&quot;"_L1;
3435 break;
3436 case u'\t':
3437 if (escapeWhitespace)
3438 replacement = "&#9;"_L1;
3439 break;
3440 case u'\n':
3441 if (escapeWhitespace)
3442 replacement = "&#10;"_L1;
3443 break;
3444 case u'\r':
3445 if (escapeWhitespace)
3446 replacement = "&#13;"_L1;
3447 break;
3448 case u'\v':
3449 case u'\f':
3450 raiseError(QXmlStreamWriter::Error::InvalidCharacter);
3451 if (stopWritingOnError)
3452 return;
3453 replacement = ""_L1;
3454 Q_ASSERT(!replacement.isNull());
3455 break;
3456 default:
3457 if (decoded.value > 0x1F)
3458 break;
3459 // ASCII control characters
3460 Q_FALLTHROUGH();
3461 case 0xFFFE:
3462 case 0xFFFF:
3463 raiseError(decoded.encodingError
3464 ? QXmlStreamWriter::Error::Encoding
3465 : QXmlStreamWriter::Error::InvalidCharacter);
3466 if (stopWritingOnError)
3467 return;
3468 replacement = ""_L1;
3469 Q_ASSERT(!replacement.isNull());
3470 break;
3471 }
3472 if (!replacement.isNull())
3473 break;
3474 it = next_it;
3475 }
3476
3477 escaped.append(View{mark, it});
3478 escaped.append(replacement);
3479 if (it != end)
3480 ++it;
3481 }
3482 } );
3483
3484 write(escaped);
3485}
3486
3487void QXmlStreamWriterPrivate::writeNamespaceDeclaration(const NamespaceDeclaration &namespaceDeclaration) {
3488 if (namespaceDeclaration.prefix.isEmpty()) {
3489 write(" xmlns=\"");
3490 write(namespaceDeclaration.namespaceUri);
3491 write("\"");
3492 } else {
3493 write(" xmlns:");
3494 write(namespaceDeclaration.prefix);
3495 write("=\"");
3496 write(namespaceDeclaration.namespaceUri);
3497 write("\"");
3498 }
3499 didWriteAnyToken = true;
3500}
3501
3502bool QXmlStreamWriterPrivate::finishStartElement(bool contents)
3503{
3504 bool hadSomethingWritten = wroteSomething;
3505 wroteSomething = contents;
3506 if (!inStartElement)
3507 return hadSomethingWritten;
3508
3509 if (inEmptyElement) {
3510 write("/>");
3511 QXmlStreamWriterPrivate::Tag tag = tagStack_pop();
3512 lastNamespaceDeclaration = tag.namespaceDeclarationsSize;
3513 lastWasStartElement = false;
3514 } else {
3515 write(">");
3516 }
3517 inStartElement = inEmptyElement = false;
3518 lastNamespaceDeclaration = namespaceDeclarations.size();
3519 didWriteAnyToken = true;
3520 return hadSomethingWritten;
3521}
3522
3523QXmlStreamPrivateTagStack::NamespaceDeclaration &
3524QXmlStreamWriterPrivate::addExtraNamespace(QAnyStringView namespaceUri, QAnyStringView prefix)
3525{
3526 const bool prefixIsXml = prefix == "xml"_L1;
3527 const bool namespaceUriIsXml = namespaceUri == "http://www.w3.org/XML/1998/namespace"_L1;
3528 if (prefixIsXml && !namespaceUriIsXml) {
3529 qWarning("Reserved prefix 'xml' must not be bound to a different namespace name "
3530 "than 'http://www.w3.org/XML/1998/namespace'");
3531 } else if (!prefixIsXml && namespaceUriIsXml) {
3532 const QString prefixString = prefix.toString();
3533 qWarning("The prefix '%ls' must not be bound to namespace name "
3534 "'http://www.w3.org/XML/1998/namespace' which 'xml' is already bound to",
3535 qUtf16Printable(prefixString));
3536 }
3537 if (namespaceUri == "http://www.w3.org/2000/xmlns/"_L1) {
3538 const QString prefixString = prefix.toString();
3539 qWarning("The prefix '%ls' must not be bound to namespace name "
3540 "'http://www.w3.org/2000/xmlns/'",
3541 qUtf16Printable(prefixString));
3542 }
3543 auto &namespaceDeclaration = namespaceDeclarations.push();
3544 namespaceDeclaration.prefix = addToStringStorage(prefix);
3545 namespaceDeclaration.namespaceUri = addToStringStorage(namespaceUri);
3546 return namespaceDeclaration;
3547}
3548
3549QXmlStreamPrivateTagStack::NamespaceDeclaration &QXmlStreamWriterPrivate::findNamespace(QAnyStringView namespaceUri, bool writeDeclaration, bool noDefault)
3550{
3551 for (NamespaceDeclaration &namespaceDeclaration : reversed(namespaceDeclarations)) {
3552 if (namespaceDeclaration.namespaceUri == namespaceUri) {
3553 if (!noDefault || !namespaceDeclaration.prefix.isEmpty())
3554 return namespaceDeclaration;
3555 }
3556 }
3557 if (namespaceUri.isEmpty())
3558 return emptyNamespace;
3559 NamespaceDeclaration &namespaceDeclaration = namespaceDeclarations.push();
3560 if (namespaceUri.isEmpty()) {
3561 namespaceDeclaration.prefix.clear();
3562 } else {
3563 QString s;
3564 int n = ++namespacePrefixCount;
3565 forever {
3566 s = u'n' + QString::number(n++);
3567 qsizetype j = namespaceDeclarations.size() - 2;
3568 while (j >= 0 && namespaceDeclarations.at(j).prefix != s)
3569 --j;
3570 if (j < 0)
3571 break;
3572 }
3573 namespaceDeclaration.prefix = addToStringStorage(s);
3574 }
3575 namespaceDeclaration.namespaceUri = addToStringStorage(namespaceUri);
3576 if (writeDeclaration)
3577 writeNamespaceDeclaration(namespaceDeclaration);
3578 return namespaceDeclaration;
3579}
3580
3581
3582
3583void QXmlStreamWriterPrivate::indent(int level)
3584{
3585 if (didWriteStartDocument || didWriteAnyToken)
3586 write("\n");
3587 for (int i = 0; i < level; ++i)
3588 write(autoFormattingIndent);
3589}
3590
3591void QXmlStreamWriterPrivate::doWriteToDevice(QStringView s)
3592{
3593 constexpr qsizetype MaxChunkSize = 512;
3594 char buffer [3 * MaxChunkSize];
3595 QStringEncoder::State state;
3596 while (!s.isEmpty()) {
3597 const qsizetype chunkSize = std::min(s.size(), MaxChunkSize);
3598 char *end = QUtf8::convertFromUnicode(buffer, s.first(chunkSize), &state);
3599 doWriteToDevice(QUtf8StringView{buffer, end});
3600 s = s.sliced(chunkSize);
3601 }
3602 if (state.remainingChars > 0)
3603 raiseError(QXmlStreamWriter::Error::Encoding);
3604}
3605
3606void QXmlStreamWriterPrivate::doWriteToDevice(QUtf8StringView s)
3607{
3608 QByteArrayView bytes = s;
3609 if (device->write(bytes.data(), bytes.size()) != bytes.size())
3610 raiseError(QXmlStreamWriter::Error::IO);
3611}
3612
3613void QXmlStreamWriterPrivate::doWriteToDevice(QLatin1StringView s)
3614{
3615 constexpr qsizetype MaxChunkSize = 512;
3616 char buffer [2 * MaxChunkSize];
3617 while (!s.isEmpty()) {
3618 const qsizetype chunkSize = std::min(s.size(), MaxChunkSize);
3619 char *end = QUtf8::convertFromLatin1(buffer, s.first(chunkSize));
3620 doWriteToDevice(QUtf8StringView{buffer, end});
3621 s = s.sliced(chunkSize);
3622 }
3623}
3624
3625/*!
3626 Constructs a stream writer.
3627
3628 \sa setDevice()
3629 */
3630QXmlStreamWriter::QXmlStreamWriter()
3631 : d_ptr(new QXmlStreamWriterPrivate(this))
3632{
3633}
3634
3635/*!
3636 Constructs a stream writer that writes into \a device;
3637 */
3638QXmlStreamWriter::QXmlStreamWriter(QIODevice *device)
3639 : d_ptr(new QXmlStreamWriterPrivate(this))
3640{
3641 Q_D(QXmlStreamWriter);
3642 d->device = device;
3643}
3644
3645/*! Constructs a stream writer that writes into \a array. This is the
3646 same as creating an xml writer that operates on a QBuffer device
3647 which in turn operates on \a array.
3648 */
3649QXmlStreamWriter::QXmlStreamWriter(QByteArray *array)
3650 : d_ptr(new QXmlStreamWriterPrivate(this))
3651{
3652 Q_D(QXmlStreamWriter);
3653 d->device = new QBuffer(array);
3654 d->device->open(QIODevice::WriteOnly);
3655 d->deleteDevice = true;
3656}
3657
3658
3659/*! Constructs a stream writer that writes into \a string.
3660 */
3661QXmlStreamWriter::QXmlStreamWriter(QString *string)
3662 : d_ptr(new QXmlStreamWriterPrivate(this))
3663{
3664 Q_D(QXmlStreamWriter);
3665 d->stringDevice = string;
3666}
3667
3668/*!
3669 Destructor.
3670*/
3671QXmlStreamWriter::~QXmlStreamWriter()
3672{
3673}
3674
3675
3676/*!
3677 Sets the current device to \a device. If you want the stream to
3678 write into a QByteArray, you can create a QBuffer device.
3679
3680 \sa device()
3681*/
3682void QXmlStreamWriter::setDevice(QIODevice *device)
3683{
3684 Q_D(QXmlStreamWriter);
3685 if (device == d->device)
3686 return;
3687 d->stringDevice = nullptr;
3688 if (d->deleteDevice) {
3689 delete d->device;
3690 d->deleteDevice = false;
3691 }
3692 d->device = device;
3693}
3694
3695/*!
3696 Returns the current device associated with the QXmlStreamWriter,
3697 or \nullptr if no device has been assigned.
3698
3699 \sa setDevice()
3700*/
3701QIODevice *QXmlStreamWriter::device() const
3702{
3703 Q_D(const QXmlStreamWriter);
3704 return d->device;
3705}
3706
3707/*!
3708 \property QXmlStreamWriter::autoFormatting
3709 \since 4.4
3710 \brief the auto-formatting flag of the stream writer.
3711
3712 This property controls whether or not the stream writer
3713 automatically formats the generated XML data. If enabled, the
3714 writer automatically adds line-breaks and indentation to empty
3715 sections between elements (ignorable whitespace). The main purpose
3716 of auto-formatting is to split the data into several lines, and to
3717 increase readability for a human reader. The indentation depth can
3718 be controlled through the \l autoFormattingIndent property.
3719
3720 By default, auto-formatting is disabled.
3721*/
3722
3723/*!
3724 \since 4.4
3725
3726 Enables auto formatting if \a enable is \c true, otherwise
3727 disables it.
3728
3729 The default value is \c false.
3730 */
3731void QXmlStreamWriter::setAutoFormatting(bool enable)
3732{
3733 Q_D(QXmlStreamWriter);
3734 d->autoFormatting = enable;
3735}
3736
3737/*!
3738 \since 4.4
3739
3740 Returns \c true if auto formatting is enabled, otherwise \c false.
3741 */
3742bool QXmlStreamWriter::autoFormatting() const
3743{
3744 Q_D(const QXmlStreamWriter);
3745 return d->autoFormatting;
3746}
3747
3748/*!
3749 \property QXmlStreamWriter::autoFormattingIndent
3750 \since 4.4
3751
3752 \brief the number of spaces or tabs used for indentation when
3753 auto-formatting is enabled. Positive numbers indicate spaces,
3754 negative numbers tabs.
3755
3756 The default indentation is 4.
3757
3758 \sa autoFormatting
3759*/
3760
3761
3762void QXmlStreamWriter::setAutoFormattingIndent(int spacesOrTabs)
3763{
3764 Q_D(QXmlStreamWriter);
3765 d->autoFormattingIndent.assign(size_t(qAbs(spacesOrTabs)), spacesOrTabs >= 0 ? ' ' : '\t');
3766}
3767
3768int QXmlStreamWriter::autoFormattingIndent() const
3769{
3770 Q_D(const QXmlStreamWriter);
3771 const QLatin1StringView indent(d->autoFormattingIndent);
3772 return indent.count(u' ') - indent.count(u'\t');
3773}
3774
3775/*!
3776 \property QXmlStreamWriter::stopWritingOnError
3777 \since 6.10
3778
3779 \brief The option to stop writing to the device after encountering an error.
3780
3781 If this property is set to \c true, the writer stops writing immediately upon
3782 encountering any error and ignores all subsequent write operations.
3783 When this property is set to \c false, the writer may continue writing
3784 after an error, skipping the invalid write but allowing further output.
3785
3786 Note that this includes \l Error::InvalidCharacter, \l Error::Encoding,
3787 and \l Error::Custom. \l Error::IO is always considered terminal
3788 and stops writing regardless of this setting.
3789
3790 The default value is \c false.
3791 */
3792bool QXmlStreamWriter::stopWritingOnError() const
3793{
3794 Q_D(const QXmlStreamWriter);
3795 return d->stopWritingOnError;
3796}
3797
3798void QXmlStreamWriter::setStopWritingOnError(bool stop)
3799{
3800 Q_D(QXmlStreamWriter);
3801 d->stopWritingOnError = stop;
3802}
3803
3804/*!
3805 Returns \c true if an error occurred while trying to write data.
3806
3807 If the error is \l Error::IO, subsequent writes to the underlying
3808 QIODevice will fail. In other cases malformed data might be written to
3809 the document.
3810
3811 The error status is never reset. Writes happening after the error
3812 occurred may be ignored, even if the error condition is cleared.
3813
3814 \sa error(), errorString(), raiseError()
3815 */
3816bool QXmlStreamWriter::hasError() const
3817{
3818 return error() != QXmlStreamWriter::Error::None;
3819}
3820
3821/*!
3822 Returns the current error state of the writer.
3823
3824 If no error has occurred, this function returns
3825 QXmlStreamWriter::Error::None.
3826
3827 \since 6.10
3828 \sa errorString(), raiseError(), hasError()
3829 */
3830QXmlStreamWriter::Error QXmlStreamWriter::error() const
3831{
3832 Q_D(const QXmlStreamWriter);
3833 return d->error;
3834}
3835
3836/*!
3837 If an error has occurred, returns its associated error message.
3838
3839 The error message is either set internally by QXmlStreamWriter or provided
3840 by the user via raiseError(). If no error has occurred, this function returns
3841 a null string.
3842
3843 \since 6.10
3844 \sa error(), raiseError(), hasError()
3845 */
3846QString QXmlStreamWriter::errorString() const
3847{
3848 Q_D(const QXmlStreamWriter);
3849 return d->errorString;
3850}
3851
3852/*!
3853 Raises a custom error with the given \a message.
3854
3855 This function is for manual indication that an error has occurred during
3856 writing, such as an application level validation failure.
3857
3858 \since 6.10
3859 \sa errorString(), error(), hasError()
3860 */
3861void QXmlStreamWriter::raiseError(QAnyStringView message)
3862{
3863 Q_D(QXmlStreamWriter);
3864 d->raiseError(QXmlStreamWriter::Error::Custom, message);
3865}
3866
3867/*!
3868 \overload
3869 Writes an attribute with \a qualifiedName and \a value.
3870
3871
3872 This function can only be called after writeStartElement() before
3873 any content is written, or after writeEmptyElement().
3874
3875 \note In Qt versions prior to 6.5, this function took QString, not
3876 QAnyStringView.
3877 */
3878void QXmlStreamWriter::writeAttribute(QAnyStringView qualifiedName, QAnyStringView value)
3879{
3880 Q_D(QXmlStreamWriter);
3881 Q_ASSERT(d->inStartElement);
3882 Q_ASSERT(count(qualifiedName, ':') <= 1);
3883 d->write(" ");
3884 d->write(qualifiedName);
3885 d->write("=\"");
3886 d->writeEscaped(value, true);
3887 d->write("\"");
3888 d->didWriteAnyToken = true;
3889}
3890
3891/*! Writes an attribute with \a name and \a value, prefixed for
3892 the specified \a namespaceUri. If the namespace has not been
3893 declared yet, QXmlStreamWriter will generate a namespace declaration
3894 for it.
3895
3896 This function can only be called after writeStartElement() before
3897 any content is written, or after writeEmptyElement().
3898
3899 \note In Qt versions prior to 6.5, this function took QString, not
3900 QAnyStringView.
3901 */
3902void QXmlStreamWriter::writeAttribute(QAnyStringView namespaceUri, QAnyStringView name, QAnyStringView value)
3903{
3904 Q_D(QXmlStreamWriter);
3905 Q_ASSERT(d->inStartElement);
3906 Q_ASSERT(!contains(name, ':'));
3907 QXmlStreamWriterPrivate::NamespaceDeclaration &namespaceDeclaration = d->findNamespace(namespaceUri, true, true);
3908 d->write(" ");
3909 if (!namespaceDeclaration.prefix.isEmpty()) {
3910 d->write(namespaceDeclaration.prefix);
3911 d->write(":");
3912 }
3913 d->write(name);
3914 d->write("=\"");
3915 d->writeEscaped(value, true);
3916 d->write("\"");
3917 d->didWriteAnyToken = true;
3918}
3919
3920/*!
3921 \overload
3922
3923 Writes the \a attribute.
3924
3925 This function can only be called after writeStartElement() before
3926 any content is written, or after writeEmptyElement().
3927 */
3928void QXmlStreamWriter::writeAttribute(const QXmlStreamAttribute& attribute)
3929{
3930 if (attribute.namespaceUri().isEmpty())
3931 writeAttribute(attribute.qualifiedName(), attribute.value());
3932 else
3933 writeAttribute(attribute.namespaceUri(), attribute.name(), attribute.value());
3934}
3935
3936
3937/*! Writes the attribute vector \a attributes. If a namespace
3938 referenced in an attribute not been declared yet, QXmlStreamWriter
3939 will generate a namespace declaration for it.
3940
3941 This function can only be called after writeStartElement() before
3942 any content is written, or after writeEmptyElement().
3943
3944 \sa writeAttribute(), writeNamespace()
3945 */
3946void QXmlStreamWriter::writeAttributes(const QXmlStreamAttributes& attributes)
3947{
3948 Q_D(QXmlStreamWriter);
3949 Q_ASSERT(d->inStartElement);
3950 Q_UNUSED(d);
3951 for (const auto &attr : attributes)
3952 writeAttribute(attr);
3953}
3954
3955
3956/*! Writes \a text as CDATA section. If \a text contains the
3957 forbidden character sequence "]]>", it is split into different CDATA
3958 sections.
3959
3960 This function mainly exists for completeness. Normally you should
3961 not need use it, because writeCharacters() automatically escapes all
3962 non-content characters.
3963
3964 \note In Qt versions prior to 6.5, this function took QString, not
3965 QAnyStringView.
3966 */
3967void QXmlStreamWriter::writeCDATA(QAnyStringView text)
3968{
3969 Q_D(QXmlStreamWriter);
3970 d->finishStartElement();
3971 d->write("<![CDATA[");
3972 while (!text.isEmpty()) {
3973 const auto idx = indexOf(text, "]]>"_L1);
3974 if (idx < 0)
3975 break; // no forbidden sequence found
3976 d->write(text.first(idx));
3977 d->write("]]" // text[idx, idx + 2)
3978 "]]><![CDATA[" // escape sequence to separate ]] and >
3979 ">"); // text[idx + 2, idx + 3)
3980 text = text.sliced(idx + 3); // skip over "]]>"
3981 }
3982 d->write(text); // write remainder
3983 d->write("]]>");
3984}
3985
3986
3987/*! Writes \a text. The characters "<", "&", and "\"" are escaped as entity
3988 references "&lt;", "&amp;, and "&quot;". To avoid the forbidden sequence
3989 "]]>", ">" is also escaped as "&gt;".
3990
3991 \sa writeEntityReference()
3992
3993 \note In Qt versions prior to 6.5, this function took QString, not
3994 QAnyStringView.
3995 */
3996void QXmlStreamWriter::writeCharacters(QAnyStringView text)
3997{
3998 Q_D(QXmlStreamWriter);
3999 d->finishStartElement();
4000 d->writeEscaped(text);
4001}
4002
4003
4004/*! Writes \a text as XML comment, where \a text must not contain the
4005 forbidden sequence \c{--} or end with \c{-}. Note that XML does not
4006 provide any way to escape \c{-} in a comment.
4007
4008 \note In Qt versions prior to 6.5, this function took QString, not
4009 QAnyStringView.
4010 */
4011void QXmlStreamWriter::writeComment(QAnyStringView text)
4012{
4013 Q_D(QXmlStreamWriter);
4014 Q_ASSERT(!contains(text, "--"_L1) && !endsWith(text, '-'));
4015 if (!d->finishStartElement(false) && d->autoFormatting)
4016 d->indent(d->tagStack.size());
4017 d->write("<!--");
4018 d->write(text);
4019 d->write("-->");
4020 d->inStartElement = d->lastWasStartElement = false;
4021}
4022
4023
4024/*! Writes a DTD section. The \a dtd represents the entire
4025 doctypedecl production from the XML 1.0 specification.
4026
4027 \note In Qt versions prior to 6.5, this function took QString, not
4028 QAnyStringView.
4029 */
4030void QXmlStreamWriter::writeDTD(QAnyStringView dtd)
4031{
4032 Q_D(QXmlStreamWriter);
4033 d->finishStartElement();
4034 if (d->autoFormatting)
4035 d->write("\n");
4036 d->write(dtd);
4037 if (d->autoFormatting)
4038 d->write("\n");
4039}
4040
4041
4042
4043/*! \overload
4044 Writes an empty element with qualified name \a qualifiedName.
4045 Subsequent calls to writeAttribute() will add attributes to this element.
4046
4047 \note In Qt versions prior to 6.5, this function took QString, not
4048 QAnyStringView.
4049*/
4050void QXmlStreamWriter::writeEmptyElement(QAnyStringView qualifiedName)
4051{
4052 Q_D(QXmlStreamWriter);
4053 Q_ASSERT(count(qualifiedName, ':') <= 1);
4054 d->writeStartElement({}, qualifiedName);
4055 d->inEmptyElement = true;
4056}
4057
4058
4059/*! Writes an empty element with \a name, prefixed for the specified
4060 \a namespaceUri. If the namespace has not been declared,
4061 QXmlStreamWriter will generate a namespace declaration for it.
4062 Subsequent calls to writeAttribute() will add attributes to this element.
4063
4064 \sa writeNamespace()
4065
4066 \note In Qt versions prior to 6.5, this function took QString, not
4067 QAnyStringView.
4068 */
4069void QXmlStreamWriter::writeEmptyElement(QAnyStringView namespaceUri, QAnyStringView name)
4070{
4071 Q_D(QXmlStreamWriter);
4072 Q_ASSERT(!contains(name, ':'));
4073 d->writeStartElement(namespaceUri, name);
4074 d->inEmptyElement = true;
4075}
4076
4077
4078/*!\overload
4079 Writes a text element with \a qualifiedName and \a text.
4080
4081
4082 This is a convenience function equivalent to:
4083 \snippet code/src_corelib_xml_qxmlstream.cpp 1
4084
4085 \note In Qt versions prior to 6.5, this function took QString, not
4086 QAnyStringView.
4087*/
4088void QXmlStreamWriter::writeTextElement(QAnyStringView qualifiedName, QAnyStringView text)
4089{
4090 writeStartElement(qualifiedName);
4091 writeCharacters(text);
4092 writeEndElement();
4093}
4094
4095/*! Writes a text element with \a name, prefixed for the specified \a
4096 namespaceUri, and \a text. If the namespace has not been
4097 declared, QXmlStreamWriter will generate a namespace declaration
4098 for it.
4099
4100
4101 This is a convenience function equivalent to:
4102 \snippet code/src_corelib_xml_qxmlstream.cpp 2
4103
4104 \note In Qt versions prior to 6.5, this function took QString, not
4105 QAnyStringView.
4106*/
4107void QXmlStreamWriter::writeTextElement(QAnyStringView namespaceUri, QAnyStringView name, QAnyStringView text)
4108{
4109 writeStartElement(namespaceUri, name);
4110 writeCharacters(text);
4111 writeEndElement();
4112}
4113
4114
4115/*!
4116 Closes all remaining open start elements and writes a newline.
4117
4118 \sa writeStartDocument()
4119 */
4120void QXmlStreamWriter::writeEndDocument()
4121{
4122 Q_D(QXmlStreamWriter);
4123 while (d->tagStack.size())
4124 writeEndElement();
4125 if (d->didWriteStartDocument || d->didWriteAnyToken)
4126 d->write("\n");
4127}
4128
4129/*!
4130 Closes the previous start element.
4131
4132 \sa writeStartElement()
4133 */
4134void QXmlStreamWriter::writeEndElement()
4135{
4136 Q_D(QXmlStreamWriter);
4137 Q_ASSERT(d->didWriteAnyToken);
4138 if (d->tagStack.isEmpty())
4139 return;
4140
4141 // shortcut: if nothing was written, close as empty tag
4142 if (d->inStartElement && !d->inEmptyElement) {
4143 d->write("/>");
4144 d->lastWasStartElement = d->inStartElement = false;
4145 QXmlStreamWriterPrivate::Tag tag = d->tagStack_pop();
4146 d->lastNamespaceDeclaration = tag.namespaceDeclarationsSize;
4147 return;
4148 }
4149
4150 if (!d->finishStartElement(false) && !d->lastWasStartElement && d->autoFormatting)
4151 d->indent(d->tagStack.size()-1);
4152 if (d->tagStack.isEmpty())
4153 return;
4154 d->lastWasStartElement = false;
4155 QXmlStreamWriterPrivate::Tag tag = d->tagStack_pop();
4156 d->lastNamespaceDeclaration = tag.namespaceDeclarationsSize;
4157 d->write("</");
4158 if (!tag.namespaceDeclaration.prefix.isEmpty()) {
4159 d->write(tag.namespaceDeclaration.prefix);
4160 d->write(":");
4161 }
4162 d->write(tag.name);
4163 d->write(">");
4164}
4165
4166
4167
4168/*!
4169 Writes the entity reference \a name to the stream, as "&\a{name};".
4170
4171 \note In Qt versions prior to 6.5, this function took QString, not
4172 QAnyStringView.
4173 */
4174void QXmlStreamWriter::writeEntityReference(QAnyStringView name)
4175{
4176 Q_D(QXmlStreamWriter);
4177 d->finishStartElement();
4178 d->write("&");
4179 d->write(name);
4180 d->write(";");
4181}
4182
4183
4184/*! Writes a namespace declaration for \a namespaceUri with \a
4185 prefix. If \a prefix is empty, QXmlStreamWriter assigns a unique
4186 prefix consisting of the letter 'n' followed by a number.
4187
4188 If writeStartElement() or writeEmptyElement() was called, the
4189 declaration applies to the current element; otherwise it applies to
4190 the next child element.
4191
4192 Note that the prefix \e xml is both predefined and reserved for
4193 \e http://www.w3.org/XML/1998/namespace, which in turn cannot be
4194 bound to any other prefix. The prefix \e xmlns and its URI
4195 \e http://www.w3.org/2000/xmlns/ are used for the namespace mechanism
4196 itself and thus completely forbidden in declarations.
4197
4198 \note In Qt versions prior to 6.5, this function took QString, not
4199 QAnyStringView.
4200 */
4201void QXmlStreamWriter::writeNamespace(QAnyStringView namespaceUri, QAnyStringView prefix)
4202{
4203 Q_D(QXmlStreamWriter);
4204 Q_ASSERT(prefix != "xmlns"_L1);
4205 if (prefix.isEmpty()) {
4206 d->findNamespace(namespaceUri, d->inStartElement);
4207 } else {
4208 auto &namespaceDeclaration = d->addExtraNamespace(namespaceUri, prefix);
4209 if (d->inStartElement)
4210 d->writeNamespaceDeclaration(namespaceDeclaration);
4211 }
4212}
4213
4214
4215/*! Writes a default namespace declaration for \a namespaceUri.
4216
4217 If writeStartElement() or writeEmptyElement() was called, the
4218 declaration applies to the current element; otherwise it applies to
4219 the next child element.
4220
4221 Note that the namespaces \e http://www.w3.org/XML/1998/namespace
4222 (bound to \e xmlns) and \e http://www.w3.org/2000/xmlns/ (bound to
4223 \e xml) by definition cannot be declared as default.
4224
4225 \note In Qt versions prior to 6.5, this function took QString, not
4226 QAnyStringView.
4227 */
4228void QXmlStreamWriter::writeDefaultNamespace(QAnyStringView namespaceUri)
4229{
4230 Q_D(QXmlStreamWriter);
4231 Q_ASSERT(namespaceUri != "http://www.w3.org/XML/1998/namespace"_L1);
4232 Q_ASSERT(namespaceUri != "http://www.w3.org/2000/xmlns/"_L1);
4233 QXmlStreamWriterPrivate::NamespaceDeclaration &namespaceDeclaration = d->namespaceDeclarations.push();
4234 namespaceDeclaration.prefix.clear();
4235 namespaceDeclaration.namespaceUri = d->addToStringStorage(namespaceUri);
4236 if (d->inStartElement)
4237 d->writeNamespaceDeclaration(namespaceDeclaration);
4238}
4239
4240
4241/*!
4242 Writes an XML processing instruction with \a target and \a data,
4243 where \a data must not contain the sequence "?>".
4244
4245 \note In Qt versions prior to 6.5, this function took QString, not
4246 QAnyStringView.
4247 */
4248void QXmlStreamWriter::writeProcessingInstruction(QAnyStringView target, QAnyStringView data)
4249{
4250 Q_D(QXmlStreamWriter);
4251 Q_ASSERT(!contains(data, "?>"_L1));
4252 if (!d->finishStartElement(false) && d->autoFormatting)
4253 d->indent(d->tagStack.size());
4254 d->write("<?");
4255 d->write(target);
4256 if (!data.isNull()) {
4257 d->write(" ");
4258 d->write(data);
4259 }
4260 d->write("?>");
4261 d->didWriteAnyToken = true;
4262}
4263
4264
4265
4266/*!\overload
4267
4268 Writes a document start with XML version number "1.0".
4269
4270 \sa writeEndDocument()
4271 \since 4.5
4272 */
4273void QXmlStreamWriter::writeStartDocument()
4274{
4275 writeStartDocument("1.0"_L1);
4276}
4277
4278
4279/*!
4280 Writes a document start with the XML version number \a version.
4281
4282 \note This function does not validate the version string and
4283 allows setting it manually. However, QXmlStreamWriter only
4284 supports XML 1.0. Setting a version string
4285 other than "1.0" does not change the writer's behavior or
4286 escaping rules. It is the caller's responsibility to ensure
4287 consistency between the declared version and the actual content.
4288
4289
4290 \note In Qt versions prior to 6.5, this function took QString, not
4291 QAnyStringView.
4292
4293 \sa writeEndDocument()
4294 */
4295void QXmlStreamWriter::writeStartDocument(QAnyStringView version)
4296{
4297 Q_D(QXmlStreamWriter);
4298 d->finishStartElement(false);
4299 d->write("<?xml version=\"");
4300 d->write(version);
4301 if (d->device) // stringDevice does not get any encoding
4302 d->write("\" encoding=\"UTF-8");
4303 d->write("\"?>");
4304 d->didWriteStartDocument = true;
4305}
4306
4307/*!
4308 \since 4.5
4309 Writes a document start with the XML version number \a version
4310 and a standalone attribute \a standalone.
4311
4312 \note This function does not validate the version string and
4313 allows setting it manually. However, QXmlStreamWriter only
4314 supports XML 1.0. Setting a version string
4315 other than "1.0" does not change the writer's behavior or
4316 escaping rules. It is the caller's responsibility to ensure
4317 consistency between the declared version and the actual content.
4318
4319
4320 \note In Qt versions prior to 6.5, this function took QString, not
4321 QAnyStringView.
4322
4323 \sa writeEndDocument()
4324 */
4325void QXmlStreamWriter::writeStartDocument(QAnyStringView version, bool standalone)
4326{
4327 Q_D(QXmlStreamWriter);
4328 d->finishStartElement(false);
4329 d->write("<?xml version=\"");
4330 d->write(version);
4331 if (d->device) // stringDevice does not get any encoding
4332 d->write("\" encoding=\"UTF-8");
4333 if (standalone)
4334 d->write("\" standalone=\"yes\"?>");
4335 else
4336 d->write("\" standalone=\"no\"?>");
4337 d->didWriteStartDocument = true;
4338}
4339
4340
4341/*!\overload
4342
4343 Writes a start element with \a qualifiedName. Subsequent calls to
4344 writeAttribute() will add attributes to this element.
4345
4346 \sa writeEndElement(), writeEmptyElement()
4347
4348 \note In Qt versions prior to 6.5, this function took QString, not
4349 QAnyStringView.
4350 */
4351void QXmlStreamWriter::writeStartElement(QAnyStringView qualifiedName)
4352{
4353 Q_D(QXmlStreamWriter);
4354 Q_ASSERT(count(qualifiedName, ':') <= 1);
4355 d->writeStartElement({}, qualifiedName);
4356}
4357
4358
4359/*! Writes a start element with \a name, prefixed for the specified
4360 \a namespaceUri. If the namespace has not been declared yet,
4361 QXmlStreamWriter will generate a namespace declaration for
4362 it. Subsequent calls to writeAttribute() will add attributes to this
4363 element.
4364
4365 \sa writeNamespace(), writeEndElement(), writeEmptyElement()
4366
4367 \note In Qt versions prior to 6.5, this function took QString, not
4368 QAnyStringView.
4369 */
4370void QXmlStreamWriter::writeStartElement(QAnyStringView namespaceUri, QAnyStringView name)
4371{
4372 Q_D(QXmlStreamWriter);
4373 Q_ASSERT(!contains(name, ':'));
4374 d->writeStartElement(namespaceUri, name);
4375}
4376
4377void QXmlStreamWriterPrivate::writeStartElement(QAnyStringView namespaceUri, QAnyStringView name,
4378 StartElementOption option)
4379{
4380 if (!finishStartElement(false) && autoFormatting)
4381 indent(tagStack.size());
4382
4383 Tag &tag = tagStack_push();
4384 tag.name = addToStringStorage(name);
4385 tag.namespaceDeclaration = findNamespace(namespaceUri);
4386 write("<");
4387 if (!tag.namespaceDeclaration.prefix.isEmpty()) {
4388 write(tag.namespaceDeclaration.prefix);
4389 write(":");
4390 }
4391 write(tag.name);
4392 inStartElement = lastWasStartElement = true;
4393
4394 if (option != StartElementOption::OmitNamespaceDeclarations) {
4395 for (qsizetype i = lastNamespaceDeclaration; i < namespaceDeclarations.size(); ++i)
4396 writeNamespaceDeclaration(namespaceDeclarations[i]);
4397 }
4398 tag.namespaceDeclarationsSize = lastNamespaceDeclaration;
4399 didWriteAnyToken = true;
4400}
4401
4402#if QT_CONFIG(xmlstreamreader)
4403/*! Writes the current state of the \a reader. All possible valid
4404 states are supported.
4405
4406 The purpose of this function is to support chained processing of XML data.
4407
4408 \sa QXmlStreamReader::tokenType()
4409 */
4410void QXmlStreamWriter::writeCurrentToken(const QXmlStreamReader &reader)
4411{
4412 Q_D(QXmlStreamWriter);
4413 switch (reader.tokenType()) {
4414 case QXmlStreamReader::NoToken:
4415 break;
4416 case QXmlStreamReader::StartDocument:
4417 writeStartDocument();
4418 break;
4419 case QXmlStreamReader::EndDocument:
4420 writeEndDocument();
4421 break;
4422 case QXmlStreamReader::StartElement: {
4423 // Namespaces must be added before writeStartElement is called so new prefixes are found
4424 QList<QXmlStreamPrivateTagStack::NamespaceDeclaration> extraNamespaces;
4425 const QXmlStreamNamespaceDeclarations nsDeclarations = reader.namespaceDeclarations();
4426 for (const auto &namespaceDeclaration : nsDeclarations) {
4427 auto &extraNamespace = d->addExtraNamespace(namespaceDeclaration.namespaceUri(),
4428 namespaceDeclaration.prefix());
4429 extraNamespaces.append(extraNamespace);
4430 }
4431 d->writeStartElement(
4432 reader.namespaceUri(), reader.name(),
4433 QXmlStreamWriterPrivate::StartElementOption::OmitNamespaceDeclarations);
4434 // Namespace declarations are written afterwards
4435 for (const auto &extraNamespace : std::as_const(extraNamespaces))
4436 d->writeNamespaceDeclaration(extraNamespace);
4437 writeAttributes(reader.attributes());
4438 } break;
4439 case QXmlStreamReader::EndElement:
4440 writeEndElement();
4441 break;
4442 case QXmlStreamReader::Characters:
4443 if (reader.isCDATA())
4444 writeCDATA(reader.text());
4445 else
4446 writeCharacters(reader.text());
4447 break;
4448 case QXmlStreamReader::Comment:
4449 writeComment(reader.text());
4450 break;
4451 case QXmlStreamReader::DTD:
4452 writeDTD(reader.text());
4453 break;
4454 case QXmlStreamReader::EntityReference:
4455 writeEntityReference(reader.name());
4456 break;
4457 case QXmlStreamReader::ProcessingInstruction:
4458 writeProcessingInstruction(reader.processingInstructionTarget(),
4459 reader.processingInstructionData());
4460 break;
4461 default:
4462 Q_ASSERT(reader.tokenType() != QXmlStreamReader::Invalid);
4463 qWarning("QXmlStreamWriter: writeCurrentToken() with invalid state.");
4464 break;
4465 }
4466}
4467#endif // feature xmlstreamreader
4468#endif // feature xmlstreamwriter
4469
4470#if QT_CONFIG(xmlstreamreader)
4471static constexpr bool isTokenAllowedInContext(QXmlStreamReader::TokenType type,
4472 QXmlStreamReaderPrivate::XmlContext ctxt)
4473{
4474 switch (type) {
4475 case QXmlStreamReader::StartDocument:
4476 case QXmlStreamReader::DTD:
4477 return ctxt == QXmlStreamReaderPrivate::XmlContext::Prolog;
4478
4479 case QXmlStreamReader::StartElement:
4480 case QXmlStreamReader::EndElement:
4481 case QXmlStreamReader::Characters:
4482 case QXmlStreamReader::EntityReference:
4483 case QXmlStreamReader::EndDocument:
4484 return ctxt == QXmlStreamReaderPrivate::XmlContext::Body;
4485
4486 case QXmlStreamReader::Comment:
4487 case QXmlStreamReader::ProcessingInstruction:
4488 return true;
4489
4490 case QXmlStreamReader::NoToken:
4491 case QXmlStreamReader::Invalid:
4492 return false;
4493 }
4494
4495 // GCC 8.x does not treat __builtin_unreachable() as constexpr
4496#if !defined(Q_CC_GNU_ONLY) || (Q_CC_GNU >= 900)
4497 Q_UNREACHABLE_RETURN(false);
4498#else
4499 return false;
4500#endif
4501}
4502
4503/*!
4504 \internal
4505 \brief QXmlStreamReader::isValidToken
4506 \return \c true if \param type is a valid token type.
4507 \return \c false if \param type is an unexpected token,
4508 which indicates a non-well-formed or invalid XML stream.
4509 */
4510bool QXmlStreamReaderPrivate::isValidToken(QXmlStreamReader::TokenType type)
4511{
4512 // Don't change currentContext, if Invalid or NoToken occur in the prolog
4513 if (type == QXmlStreamReader::Invalid || type == QXmlStreamReader::NoToken)
4514 return false;
4515
4516 // If a token type gets rejected in the body, there is no recovery
4517 const bool result = isTokenAllowedInContext(type, currentContext);
4518 if (result || currentContext == XmlContext::Body)
4519 return result;
4520
4521 // First non-Prolog token observed => switch context to body and check again.
4522 currentContext = XmlContext::Body;
4523 return isTokenAllowedInContext(type, currentContext);
4524}
4525
4526/*!
4527 \internal
4528 Checks token type and raises an error, if it is invalid
4529 in the current context (prolog/body).
4530 */
4531void QXmlStreamReaderPrivate::checkToken()
4532{
4533 Q_Q(QXmlStreamReader);
4534
4535 // The token type must be consumed, to keep track if the body has been reached.
4536 const XmlContext context = currentContext;
4537 const bool ok = isValidToken(type);
4538
4539 // Do nothing if an error has been raised already (going along with an unexpected token)
4540 if (error != QXmlStreamReader::Error::NoError)
4541 return;
4542
4543 if (!ok) {
4544 raiseError(QXmlStreamReader::UnexpectedElementError,
4545 QXmlStream::tr("Unexpected token type %1 in %2.")
4546 .arg(q->tokenString(), contextString(context)));
4547 return;
4548 }
4549
4550 if (type != QXmlStreamReader::DTD)
4551 return;
4552
4553 // Raise error on multiple DTD tokens
4554 if (foundDTD) {
4555 raiseError(QXmlStreamReader::UnexpectedElementError,
4556 QXmlStream::tr("Found second DTD token in %1.").arg(contextString(context)));
4557 } else {
4558 foundDTD = true;
4559 }
4560}
4561
4562/*!
4563 \fn bool QXmlStreamAttributes::hasAttribute(QAnyStringView qualifiedName) const
4564
4565 Returns \c true if this QXmlStreamAttributes has an attribute whose
4566 qualified name is \a qualifiedName; otherwise returns \c false.
4567
4568 Note that this is not namespace aware. For instance, if this
4569 QXmlStreamAttributes contains an attribute whose lexical name is "xlink:href"
4570 this doesn't tell that an attribute named \c href in the XLink namespace is
4571 present, since the \c xlink prefix can be bound to any namespace. Use the
4572 overload that takes a namespace URI and a local name as parameter, for
4573 namespace aware code.
4574*/
4575
4576/*!
4577 \fn bool QXmlStreamAttributes::hasAttribute(QAnyStringView namespaceUri,
4578 QAnyStringView name) const
4579 \overload
4580
4581 Returns \c true if this QXmlStreamAttributes has an attribute whose
4582 namespace URI and name correspond to \a namespaceUri and \a name;
4583 otherwise returns \c false.
4584*/
4585
4586#endif // feature xmlstreamreader
4587
4588QT_END_NAMESPACE
4589
4590#endif // feature xmlstream