5#include "QtCore/qxmlstream.h"
7#if QT_CONFIG(xmlstream)
9#include "qxmlutils_p.h"
14#include <QtCore/qspan.h>
15#include <qstringconverter.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>
25#include "qxmlstream_p.h"
26#include "qxmlstreamparser_p.h"
27#include <private/qstringconverter_p.h>
28#include <private/qstringiterator_p.h>
34using namespace QtPrivate;
35using namespace Qt::StringLiterals;
36using namespace QtMiscUtils;
38constexpr uint StreamEOF = ~0U;
41template <
typename Range>
42auto reversed(Range &r)
46 auto begin() {
return std::make_reverse_iterator(std::end(*r)); }
47 auto end() {
return std::make_reverse_iterator(std::begin(*r)); }
53template <
typename Range>
54void reversed(
const Range &&) =
delete;
57auto transform(QLatin1StringView haystack,
char needle)
59 struct R { QLatin1StringView haystack;
char16_t needle; };
60 return R{haystack, uchar(needle)};
63auto transform(QStringView haystack,
char needle)
65 struct R { QStringView haystack;
char16_t needle; };
66 return R{haystack, uchar(needle)};
69auto transform(QUtf8StringView haystack,
char needle)
71 struct R { QByteArrayView haystack;
char needle; };
72 return R{haystack, needle};
75auto transform(QLatin1StringView haystack, QLatin1StringView needle)
77 struct R { QLatin1StringView haystack; QLatin1StringView needle; };
78 return R{haystack, needle};
81auto transform(QStringView haystack, QLatin1StringView needle)
83 struct R { QStringView haystack; QLatin1StringView needle; };
84 return R{haystack, needle};
87auto transform(QUtf8StringView haystack, QLatin1StringView needle)
89 struct R { QLatin1StringView haystack; QLatin1StringView needle; };
90 return R{QLatin1StringView{QByteArrayView{haystack}}, needle};
93#define WRAP(method, Needle)
94 auto method (QAnyStringView s, Needle needle) noexcept
96 return s.visit([needle](auto s) {
97 auto r = transform(s, needle);
98 return r.haystack. method (r.needle);
105WRAP(contains, QLatin1StringView)
107WRAP(indexOf, QLatin1StringView)
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> {};
116constexpr auto encodingFor = EncodingForHelper<T>::value;
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
171
172
173
174
175
176
177
178
179
180
181
182
183
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
268
269
270QXmlStreamEntityResolver::~QXmlStreamEntityResolver()
275
276
277
278
279QString QXmlStreamEntityResolver::resolveEntity(
const QString& ,
const QString& )
287
288
289
290
291
292
293
294
296QString QXmlStreamEntityResolver::resolveUndeclaredEntity(
const QString &)
301#if QT_CONFIG(xmlstreamreader)
303QString QXmlStreamReaderPrivate::resolveUndeclaredEntity(
const QString &name)
306 return entityResolver->resolveUndeclaredEntity(name);
313
314
315
316
317
318
319
320
321
322
323
324void QXmlStreamReader::setEntityResolver(QXmlStreamEntityResolver *resolver)
326 Q_D(QXmlStreamReader);
327 d->entityResolver = resolver;
331
332
333
334
335
336
337QXmlStreamEntityResolver *QXmlStreamReader::entityResolver()
const
339 Q_D(
const QXmlStreamReader);
340 return d->entityResolver;
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
492static void warn_addData_with_device()
494 qWarning(
"QXmlStreamReader: addData() with device()");
498
499
500
501
502QXmlStreamReader::QXmlStreamReader()
503 : d_ptr(
new QXmlStreamReaderPrivate(
this))
508
509
510
511QXmlStreamReader::QXmlStreamReader(QIODevice *device)
512 : d_ptr(
new QXmlStreamReaderPrivate(
this))
518
519
520
521
522
523
524
525
528
529
530
531
532
533
534
535
536
537void QXmlStreamReaderPrivate::appendDataWithEncoding(
const QByteArray &data,
538 QStringDecoder::Encoding enc)
540 if (tryAppendViewWithEncoding(data, enc))
542 dataInfo.emplace_back(data, enc);
545bool QXmlStreamReaderPrivate::tryAppendViewWithEncoding(QByteArrayView data, QStringDecoder::Encoding enc)
551 if (!dataInfo.empty()) {
552 auto &last = dataInfo.back();
553 if (last.encoding == enc) {
554 last.buffer.append(data);
561void QXmlStreamReaderPrivate::appendViewWithEncoding(QByteArrayView data, QStringDecoder::Encoding enc)
563 if (tryAppendViewWithEncoding(data, enc))
565 dataInfo.emplace_back(data.toByteArray(), enc);
569
570
571
572
573
574
575
576QXmlStreamReader::QXmlStreamReader(QAnyStringView data)
577 : d_ptr(
new QXmlStreamReaderPrivate(
this))
583
584
585
586
587
588QXmlStreamReader::QXmlStreamReader(
const QByteArray &data, PrivateConstructorTag)
589 : d_ptr(
new QXmlStreamReaderPrivate(
this))
591 Q_D(QXmlStreamReader);
592 d->appendDataWithEncoding(data, QStringDecoder::System);
596
597
598QXmlStreamReader::~QXmlStreamReader()
600 Q_D(QXmlStreamReader);
606
607
608
609
612
613
614
615
616
617void QXmlStreamReader::setDevice(QIODevice *device)
619 Q_D(QXmlStreamReader);
620 if (d->deleteDevice) {
622 d->deleteDevice =
false;
630
631
632
633
634
635QIODevice *QXmlStreamReader::device()
const
637 Q_D(
const QXmlStreamReader);
642
643
644
645
646
647
648
649
650
652static bool isDecoderForEncoding(
const QStringDecoder &dec, QStringDecoder::Encoding enc)
657 const auto decName = dec.name();
658 if (!decName || !*decName)
661 const auto encName = QStringConverter::nameForEncoding(enc);
662 return encName && strcmp(decName, encName) == 0;
666
667
668
669
670
671
672
673
674void QXmlStreamReader::addData(QAnyStringView data)
676 Q_D(QXmlStreamReader);
678 return warn_addData_with_device();
679 data.visit([d](
auto data) {
680 d->appendViewWithEncoding(as_bytes(QSpan(data)), encodingFor<
decltype(data)>);
685
686
687
688
689
690void QXmlStreamReader::addDataImpl(
const QByteArray &data)
692 Q_D(QXmlStreamReader);
694 return warn_addData_with_device();
695 d->appendDataWithEncoding(data, QStringDecoder::System);
699
700
701
702
703
704void QXmlStreamReader::clear()
706 Q_D(QXmlStreamReader);
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730bool QXmlStreamReader::atEnd()
const
732 Q_D(
const QXmlStreamReader);
734 && ((d->type == QXmlStreamReader::Invalid && d->error == PrematureEndOfDocumentError)
735 || (d->type == QXmlStreamReader::EndDocument))) {
737 return d->device->atEnd();
739 return d->dataInfo.empty();
741 return (d->atEnd || d->type == QXmlStreamReader::Invalid);
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763QXmlStreamReader::TokenType QXmlStreamReader::readNext()
765 Q_D(QXmlStreamReader);
766 if (d->type != Invalid) {
767 if (!d->hasCheckedStartDocument)
768 if (!d->checkStartDocument())
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) {
788
789
790
791
792
793
794
795
796
797QXmlStreamReader::TokenType QXmlStreamReader::tokenType()
const
799 Q_D(
const QXmlStreamReader);
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820bool QXmlStreamReader::readNextStartElement()
822 while (readNext() != Invalid) {
823 if (isEndElement() || isEndDocument())
825 else if (isStartElement())
832
833
834
835
836
837
838
839
840
841
842void QXmlStreamReader::skipCurrentElement()
845 while (depth && readNext() != Invalid) {
848 else if (isStartElement())
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872QString QXmlStreamReader::readRawInnerData()
874 Q_D(QXmlStreamReader);
877 auto specialToEntities = [](QStringView text, QString &output) {
879 QLatin1StringView replacement;
880 const qsizetype sz = text.size();
881 for (qsizetype i = 0; i < sz; ++i) {
882 switch (text[i].unicode()) {
884 replacement =
"<"_L1;
887 replacement =
">"_L1;
890 replacement =
"&"_L1;
893 replacement =
"""_L1;
896 replacement =
"'"_L1;
902 output += text.mid(chunk, i - chunk);
903 output += replacement;
906 if (chunk < text.size())
907 output += text.mid(chunk);
910 if (isStartElement()) {
912 while (!atEnd() && depth) {
913 switch (readNext()) {
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);
929 raw +=
"</"_L1 + name() +
'>'_L1;
933 raw +=
"<![CDATA["_L1 + text() +
"]]>"_L1;
935 specialToEntities(text(), raw);
938 raw +=
"<!--"_L1 + text() +
"-->"_L1;
940 case EntityReference:
941 raw +=
'&'_L1 + name() +
';'_L1;
943 case ProcessingInstruction:
944 raw +=
"<?"_L1 + processingInstructionTarget()
945 +
' '_L1 + processingInstructionData()
951 d->raiseError(NotWellFormedError,
952 QXmlStream::tr(
"Unexpected token while "
953 "reading raw inner data."));
962static constexpr auto QXmlStreamReader_tokenTypeString = qOffsetStringArray(
973 "ProcessingInstruction"
976static constexpr auto QXmlStreamReader_XmlContextString = qOffsetStringArray(
982
983
984
985
986
987
988
989
990
993void QXmlStreamReader::setNamespaceProcessing(
bool enable)
995 Q_D(QXmlStreamReader);
996 d->namespaceProcessing = enable;
999bool QXmlStreamReader::namespaceProcessing()
const
1001 Q_D(
const QXmlStreamReader);
1002 return d->namespaceProcessing;
1006
1007
1008
1009QString QXmlStreamReader::tokenString()
const
1011 Q_D(
const QXmlStreamReader);
1012 return QLatin1StringView(QXmlStreamReader_tokenTypeString.at(d->type));
1016
1017
1018
1019static constexpr QLatin1StringView contextString(QXmlStreamReaderPrivate::XmlContext ctxt)
1021 return QLatin1StringView(QXmlStreamReader_XmlContextString.viewAt(
static_cast<
int>(ctxt)));
1026QXmlStreamPrivateTagStack::QXmlStreamPrivateTagStack()
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;
1037#if QT_CONFIG(xmlstreamreader)
1039QXmlStreamReaderPrivate::QXmlStreamReaderPrivate(QXmlStreamReader *q)
1043 deleteDevice =
false;
1045 sym_stack =
nullptr;
1046 state_stack =
nullptr;
1048 entityResolver =
nullptr;
1052void QXmlStreamReaderPrivate::init()
1055#define ADD_PREDEFINED(n, v)
1057 Entity e = Entity::createLiteral(n##_L1, v##_L1);
1058 entityHash.insert(qToStringViewIgnoringNull(e.name), std::move(e));
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();
1069 lastAttributeIsCData =
false;
1072 isEmptyElement =
false;
1073 isWhitespace =
true;
1076 hasStandalone =
false;
1078 resumeReduction = 0;
1079 state_stack[tos++] = 0;
1080 state_stack[tos] = 0;
1082 putStack.reserve(32);
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();
1094 textBuffer.reserve(256);
1098 attributes.reserve(16);
1099 lineNumber = lastLineStart = characterOffset = 0;
1102 decoder = QStringDecoder();
1103 attributeStack.clear();
1104 attributeStack.reserve(16);
1105 entityReferenceStack.clear();
1106 entityReferenceStack.reserve(16);
1108 entityParser.reset();
1109 hasCheckedStartDocument =
false;
1110 normalizeLiterals =
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();
1123 tagStackStringStorageSize = initialTagStackStringStorageSize;
1125 type = QXmlStreamReader::NoToken;
1126 error = QXmlStreamReader::NoError;
1127 currentContext = XmlContext::Prolog;
1132
1133
1134
1135void QXmlStreamReaderPrivate::parseEntity(
const QString &value)
1137 Q_Q(QXmlStreamReader);
1139 if (value.isEmpty())
1144 entityParser = std::make_unique<QXmlStreamReaderPrivate>(q);
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."));
1157inline void QXmlStreamReaderPrivate::reallocateStack()
1162 const auto newStackSize = stack_size * 2;
1164 void *p = qt_reallocarray(sym_stack, size_t(newStackSize),
sizeof(Value));
1166 sym_stack =
static_cast<Value*>(p);
1167 p = qt_reallocarray(state_stack, size_t(newStackSize),
sizeof(
int));
1169 state_stack =
static_cast<
int*>(p);
1172 stack_size = newStackSize;
1176QXmlStreamReaderPrivate::~QXmlStreamReaderPrivate()
1183inline uint QXmlStreamReaderPrivate::filterCarriageReturn()
1185 uint peekc = peekChar();
1186 if (peekc ==
'\n') {
1187 if (putStack.size())
1193 if (peekc == StreamEOF) {
1201
1202
1203
1204inline uint QXmlStreamReaderPrivate::getChar()
1207 if (putStack.size()) {
1208 c = atEnd ? StreamEOF : putStack.pop();
1210 if (readBufferPos < readBuffer.size())
1211 c = readBuffer.at(readBufferPos++).unicode();
1213 c = getChar_helper();
1219inline uint QXmlStreamReaderPrivate::peekChar()
1222 if (putStack.size()) {
1224 }
else if (readBufferPos < readBuffer.size()) {
1225 c = readBuffer.at(readBufferPos).unicode();
1227 if ((c = getChar_helper()) != StreamEOF)
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246bool QXmlStreamReaderPrivate::scanUntil(
const char *str,
short tokenToInject)
1248 const qsizetype pos = textBuffer.size();
1249 const auto oldLineNumber = lineNumber;
1252 while ((c = getChar()) != StreamEOF) {
1256 if ((c = filterCarriageReturn()) == 0)
1261 lastLineStart = characterOffset + readBufferPos;
1264 textBuffer += QChar(c);
1267 if (c < 0x20 || (c > 0xFFFD && c < 0x10000) || c > QChar::LastValidCodePoint ) {
1268 raiseWellFormedError(QXmlStream::tr(
"Invalid XML character."));
1269 lineNumber = oldLineNumber;
1272 textBuffer += QChar(c);
1277 if (c == uint(*str)) {
1279 if (tokenToInject >= 0)
1280 injectToken(tokenToInject);
1283 if (scanString(str + 1, tokenToInject,
false))
1288 putString(textBuffer, pos);
1289 textBuffer.resize(pos);
1290 lineNumber = oldLineNumber;
1294bool QXmlStreamReaderPrivate::scanString(
const char *str,
short tokenToInject,
bool requireSpace)
1299 if (c != ushort(str[n])) {
1303 putChar(ushort(str[n]));
1309 textBuffer += QLatin1StringView(str, n);
1311 const qsizetype s = fastScanSpace();
1313 qsizetype pos = textBuffer.size() - n - s;
1314 putString(textBuffer, pos);
1315 textBuffer.resize(pos);
1319 if (tokenToInject >= 0)
1320 injectToken(tokenToInject);
1324bool QXmlStreamReaderPrivate::scanAfterLangleBang()
1326 switch (peekChar()) {
1328 return scanString(spell[CDATA_START], CDATA_START,
false);
1330 return scanString(spell[DOCTYPE], DOCTYPE);
1332 return scanString(spell[ATTLIST], ATTLIST);
1334 return scanString(spell[NOTATION], NOTATION);
1336 if (scanString(spell[ELEMENT], ELEMENT))
1338 return scanString(spell[ENTITY], ENTITY);
1346bool QXmlStreamReaderPrivate::scanPublicOrSystem()
1348 switch (peekChar()) {
1350 return scanString(spell[SYSTEM], SYSTEM);
1352 return scanString(spell[PUBLIC], PUBLIC);
1359bool QXmlStreamReaderPrivate::scanNData()
1361 if (fastScanSpace()) {
1362 if (scanString(spell[NDATA], NDATA))
1369bool QXmlStreamReaderPrivate::scanAfterDefaultDecl()
1371 switch (peekChar()) {
1373 return scanString(spell[REQUIRED], REQUIRED,
false);
1375 return scanString(spell[IMPLIED], IMPLIED,
false);
1377 return scanString(spell[FIXED], FIXED,
false);
1384bool QXmlStreamReaderPrivate::scanAttType()
1386 switch (peekChar()) {
1388 return scanString(spell[CDATA], CDATA);
1390 if (scanString(spell[ID], ID))
1392 if (scanString(spell[IDREF], IDREF))
1394 return scanString(spell[IDREFS], IDREFS);
1396 if (scanString(spell[ENTITY], ENTITY))
1398 return scanString(spell[ENTITIES], ENTITIES);
1400 if (scanString(spell[NOTATION], NOTATION))
1402 if (scanString(spell[NMTOKEN], NMTOKEN))
1404 return scanString(spell[NMTOKENS], NMTOKENS);
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423inline qsizetype QXmlStreamReaderPrivate::fastScanLiteralContent()
1427 while ((c = getChar()) != StreamEOF) {
1428 switch (ushort(c)) {
1433
1437 if (filterCarriageReturn() == 0)
1442 lastLineStart = characterOffset + readBufferPos;
1446 if (normalizeLiterals)
1449 textBuffer += QChar(c);
1456 if (!(c & 0xff0000)) {
1466 textBuffer += QChar(ushort(c));
1473inline qsizetype QXmlStreamReaderPrivate::fastScanSpace()
1477 while ((c = getChar()) != StreamEOF) {
1480 if ((c = filterCarriageReturn()) == 0)
1485 lastLineStart = characterOffset + readBufferPos;
1489 textBuffer += QChar(c);
1501
1502
1503
1504
1505
1506inline qsizetype QXmlStreamReaderPrivate::fastScanContentCharList()
1510 while ((c = getChar()) != StreamEOF) {
1511 switch (ushort(c)) {
1518 isWhitespace =
false;
1519 const qsizetype pos = textBuffer.size();
1520 textBuffer += QChar(ushort(c));
1522 while ((c = getChar()) ==
']') {
1523 textBuffer += QChar(ushort(c));
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."));
1538 if ((c = filterCarriageReturn()) == 0)
1543 lastLineStart = characterOffset + readBufferPos;
1547 textBuffer += QChar(ushort(c));
1552 if (!(c & 0xff0000)) {
1562 isWhitespace =
false;
1563 textBuffer += QChar(ushort(c));
1571inline std::optional<qsizetype> QXmlStreamReaderPrivate::fastScanName(Value *val)
1575 while ((c = getChar()) != StreamEOF) {
1579 raiseNamePrefixTooLongError();
1580 return std::nullopt;
1609 if (val && val->prefix == n + 1) {
1617 if (val->prefix == 0) {
1618 val->prefix = qint16(n + 2);
1629 textBuffer += QChar(ushort(c));
1636 qsizetype pos = textBuffer.size() - n;
1637 putString(textBuffer, pos);
1638 textBuffer.resize(pos);
1642enum NameChar { NameBeginning, NameNotBeginning, NotName };
1644static const char Begi =
static_cast<
char>(NameBeginning);
1645static const char NtBg =
static_cast<
char>(NameNotBeginning);
1646static const char NotN =
static_cast<
char>(NotName);
1648static const char nameCharTable[128] =
1651 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN,
1652 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN,
1654 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN,
1655 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN,
1657 NotN, NotN, NotN, NotN, NotN, NotN, NotN, NotN,
1658 NotN, NotN, NotN, NotN, NotN, NtBg, NtBg, NotN,
1660 NtBg, NtBg, NtBg, NtBg, NtBg, NtBg, NtBg, NtBg,
1661 NtBg, NtBg, Begi, NotN, NotN, NotN, NotN, NotN,
1663 NotN, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1664 Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1666 Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1667 Begi, Begi, Begi, NotN, NotN, NotN, NotN, Begi,
1669 NotN, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1670 Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1672 Begi, Begi, Begi, Begi, Begi, Begi, Begi, Begi,
1673 Begi, Begi, Begi, NotN, NotN, NotN, NotN, NotN
1676static inline NameChar fastDetermineNameChar(QChar ch)
1678 ushort uc = ch.unicode();
1680 return static_cast<NameChar>(nameCharTable[uc]);
1682 QChar::Category cat = ch.category();
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;
1693inline qsizetype QXmlStreamReaderPrivate::fastScanNMTOKEN()
1697 while ((c = getChar()) != StreamEOF) {
1698 if (fastDetermineNameChar(QChar(c)) == NotName) {
1703 textBuffer += QChar(c);
1707 qsizetype pos = textBuffer.size() - n;
1708 putString(textBuffer, pos);
1709 textBuffer.resize(pos);
1714void QXmlStreamReaderPrivate::putString(QStringView s, qsizetype from)
1717 putString(s.mid(from));
1720 putStack.reserve(s.size());
1721 for (
auto it = s.rbegin(), end = s.rend(); it != end; ++it)
1722 putStack.rawPush() = it->unicode();
1725void QXmlStreamReaderPrivate::putStringLiteral(QStringView s)
1727 putStack.reserve(s.size());
1728 for (
auto it = s.rbegin(), end = s.rend(); it != end; ++it)
1729 putStack.rawPush() = ((LETTER << 16) | it->unicode());
1732void QXmlStreamReaderPrivate::putReplacement(QStringView s)
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);
1740 putStack.rawPush() = c;
1743void QXmlStreamReaderPrivate::putReplacementInAttributeValue(QStringView s)
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() =
' ';
1753 putStack.rawPush() = ((LETTER << 16) | c);
1757uint QXmlStreamReaderPrivate::getChar_helper()
1759 constexpr qsizetype BUFFER_SIZE = 8192;
1760 characterOffset += readBufferPos;
1762 if (readBuffer.size())
1763 readBuffer.resize(0);
1764 if (decoder.isValid())
1767 auto tryDecodeWithGlobalDecoder = [
this]() ->
bool {
1768 if (!decoder.isValid()) {
1770 if (nbytesread < 4) {
1774 auto encoding = QStringDecoder::encodingForData(rawReadBuffer, u'<');
1776 encoding = QStringDecoder::Utf8;
1777 decoder = QStringDecoder(*encoding);
1780 readBuffer = decoder(QByteArrayView(rawReadBuffer).first(nbytesread));
1782 if (lockEncoding && decoder.hasError()) {
1791 rawReadBuffer.resize(BUFFER_SIZE);
1792 qint64 nbytesreadOrMinus1 = device->read(rawReadBuffer.data() + nbytesread, BUFFER_SIZE - nbytesread);
1793 nbytesread += qMax(nbytesreadOrMinus1, qint64{0});
1800 if (!tryDecodeWithGlobalDecoder())
1802 }
else if (dataInfo.empty()) {
1806 const BufferAndEncoding bufAndEnc = dataInfo.takeFirst();
1813 if (bufAndEnc.encoding == QStringDecoder::System) {
1815 rawReadBuffer += bufAndEnc.buffer;
1817 rawReadBuffer = bufAndEnc.buffer;
1818 nbytesread = rawReadBuffer.size();
1820 if (!tryDecodeWithGlobalDecoder()) {
1822 bool hasError =
true;
1823 if (chunkDecoder.isValid() && !chunkDecoder.hasError()) {
1824 readBuffer = chunkDecoder(QByteArrayView(rawReadBuffer).first(nbytesread));
1825 hasError = chunkDecoder.hasError();
1828 raiseWellFormedError(
1829 QXmlStream::tr(
"Encountered incorrectly encoded content."));
1834 if (!isDecoderForEncoding(chunkDecoder, bufAndEnc.encoding))
1835 chunkDecoder = QStringDecoder(bufAndEnc.encoding);
1836 readBuffer = chunkDecoder(bufAndEnc.buffer);
1840 readBuffer.reserve(1);
1842 if (readBufferPos < readBuffer.size()) {
1843 ushort c = readBuffer.at(readBufferPos++).unicode();
1851XmlStringRef QXmlStreamReaderPrivate::namespaceForPrefix(QStringView prefix)
1853 for (
const NamespaceDeclaration &namespaceDeclaration : reversed(namespaceDeclarations)) {
1854 if (namespaceDeclaration.prefix == prefix) {
1855 return namespaceDeclaration.namespaceUri;
1860 if (namespaceProcessing && !prefix.isEmpty())
1861 raiseWellFormedError(QXmlStream::tr(
"Namespace prefix '%1' not declared").arg(prefix));
1864 return XmlStringRef();
1870 QStringView namespaceUri;
1872 static AttributeName fromXmlAttribute(
const QXmlStreamAttribute &a,
bool nsProcessing)
1875 return {a.name(), a.namespaceUri()};
1877 return {a.qualifiedName(), a.namespaceUri()};
1880 friend bool operator==(
const AttributeName &lhs,
const AttributeName &rhs)
noexcept
1882 return lhs.name == rhs.name
1883 && lhs.namespaceUri == rhs.namespaceUri;
1885 friend size_t qHash(
const AttributeName &key, size_t seed = 0)
noexcept
1887 return qHashMulti(seed,
1894
1895
1896void QXmlStreamReaderPrivate::resolveTag()
1898 const auto attributeStackCleaner = qScopeGuard([
this](){ attributeStack.clear(); });
1899 const qsizetype n = attributeStack.size();
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())
1909 while (i < n && symName(attributeStack[i].key) != dtdAttribute.attributeQualifiedName)
1913 if (dtdAttribute.attributePrefix.isEmpty() && dtdAttribute.attributeName ==
"xmlns"_L1) {
1914 NamespaceDeclaration &namespaceDeclaration = namespaceDeclarations.push();
1915 namespaceDeclaration.prefix.clear();
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."));
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."));
1934 namespaceDeclaration.prefix = namespacePrefix;
1935 namespaceDeclaration.namespaceUri = namespaceUri;
1940 tagStack.top().namespaceDeclaration.namespaceUri = namespaceUri = namespaceForPrefix(prefix);
1942 attributes.resize(n);
1944 Q_DECL_UNINITIALIZED
1945 QDuplicateTracker<AttributeName, 13> names(n);
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));
1955 attribute.m_name = name;
1956 attribute.m_qualifiedName = qualifiedName;
1957 attribute.m_value = value;
1959 if (!prefix.isEmpty()) {
1960 XmlStringRef attributeNamespaceUri = namespaceForPrefix(prefix);
1961 attribute.m_namespaceUri = XmlStringRef(attributeNamespaceUri);
1964 if (names.hasSeen(AttributeName::fromXmlAttribute(attribute, namespaceProcessing))) {
1965 raiseWellFormedError(QXmlStream::tr(
"Attribute '%1' redefined.").arg(attribute.qualifiedName()));
1970 for (
const DtdAttribute &dtdAttribute : dtdAttributes) {
1971 if (dtdAttribute.isNamespaceAttribute
1972 || dtdAttribute.defaultValue.isNull()
1973 || dtdAttribute.tagName != qualifiedName
1974 || dtdAttribute.attributeQualifiedName.isNull())
1977 while (i < n && symName(attributeStack[i].key) != dtdAttribute.attributeQualifiedName)
1984 QXmlStreamAttribute attribute;
1985 attribute.m_name = dtdAttribute.attributeName;
1986 attribute.m_qualifiedName = dtdAttribute.attributeQualifiedName;
1987 attribute.m_value = dtdAttribute.defaultValue;
1989 if (!dtdAttribute.attributePrefix.isEmpty()) {
1990 XmlStringRef attributeNamespaceUri = namespaceForPrefix(dtdAttribute.attributePrefix);
1991 attribute.m_namespaceUri = XmlStringRef(attributeNamespaceUri);
2000 if (namespaceProcessing && names.hasSeen(AttributeName::fromXmlAttribute(attribute,
true))) {
2001 raiseWellFormedError(QXmlStream::tr(
"Attribute '%1' redefined.").arg(attribute.qualifiedName()));
2005 attribute.m_isDefault =
true;
2006 attributes.append(std::move(attribute));
2010void QXmlStreamReaderPrivate::resolvePublicNamespaces()
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;
2023void QXmlStreamReaderPrivate::resolveDtd()
2025 publicNotationDeclarations.resize(notationDeclarations.size());
2026 for (qsizetype i = 0; i < notationDeclarations.size(); ++i) {
2027 const QXmlStreamReaderPrivate::NotationDeclaration ¬ationDeclaration = 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;
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;
2045 entityDeclarations.clear();
2046 parameterEntityHash.clear();
2049uint QXmlStreamReaderPrivate::resolveCharRef(
int symbolIndex)
2054 if (sym(symbolIndex).c ==
'x')
2055 s = symString(symbolIndex).view().sliced(1).toUInt(&ok, 16);
2057 s = symString(symbolIndex).view().toUInt(&ok, 10);
2059 ok &= (s == 0x9 || s == 0xa || s == 0xd || (s >= 0x20 && s <= 0xd7ff)
2060 || (s >= 0xe000 && s <= 0xfffd) || (s >= 0x10000 && s <= QChar::LastValidCodePoint));
2066void QXmlStreamReaderPrivate::checkPublicLiteral(QStringView publicId)
2070 const char16_t *data = publicId.utf16();
2073 for (i = publicId.size() - 1; i >= 0; --i) {
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 '\"':
2082 if (isAsciiLetterOrNumber(c))
2088 raiseWellFormedError(QXmlStream::tr(
"Unexpected character '%1' in public id literal.").arg(QChar(QLatin1Char(c))));
2092
2093
2094
2095
2096bool QXmlStreamReaderPrivate::checkStartDocument()
2098 hasCheckedStartDocument =
true;
2100 if (scanString(spell[XML], XML))
2103 type = QXmlStreamReader::StartDocument;
2105 hasCheckedStartDocument =
false;
2106 raiseError(QXmlStreamReader::PrematureEndOfDocumentError);
2111void QXmlStreamReaderPrivate::startDocument()
2114 if (documentVersion !=
"1.0"_L1) {
2115 if (documentVersion.view().contains(u' '))
2116 err = QXmlStream::tr(
"Invalid XML version string.");
2118 err = QXmlStream::tr(
"Unsupported XML version.");
2120 qsizetype n = attributeStack.size();
2123
2124
2125
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));
2133 if (prefix.isEmpty() && key ==
"encoding"_L1) {
2134 documentEncoding = value;
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);
2141 QByteArray enc = value.toString().toUtf8();
2142 if (!lockEncoding) {
2143 decoder = QStringDecoder(enc.constData());
2144 if (!decoder.isValid()) {
2148 if (!chunkDecoder.isValid() || chunkDecoder.hasError())
2149 err = QXmlStream::tr(
"Encoding %1 is unsupported").arg(value);
2151 decoder = QStringDecoder(QStringDecoder::Utf8);
2152 }
else if (!rawReadBuffer.isEmpty() && nbytesread) {
2158 QString buf = decoder(QByteArrayView(rawReadBuffer).first(nbytesread));
2159 if (!decoder.hasError())
2160 readBuffer = std::move(buf);
2164 }
else if (prefix.isEmpty() && key ==
"standalone"_L1) {
2165 hasStandalone =
true;
2166 if (value ==
"yes"_L1)
2168 else if (value ==
"no"_L1)
2171 err = QXmlStream::tr(
"Standalone accepts only yes or no.");
2173 err = QXmlStream::tr(
"Invalid attribute in XML declaration: %1 = %2").arg(key).arg(value);
2178 raiseWellFormedError(err);
2179 attributeStack.clear();
2183void QXmlStreamReaderPrivate::raiseError(QXmlStreamReader::Error error,
const QString& message)
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.");
2194 type = QXmlStreamReader::Invalid;
2197void QXmlStreamReaderPrivate::raiseWellFormedError(
const QString &message)
2199 raiseError(QXmlStreamReader::NotWellFormedError, message);
2202void QXmlStreamReaderPrivate::raiseNamePrefixTooLongError()
2205 raiseError(QXmlStreamReader::NotWellFormedError,
2206 QXmlStream::tr(
"Length of XML attribute name exceeds implementation limits (4KiB "
2210void QXmlStreamReaderPrivate::parseError()
2213 if (token == EOF_SYMBOL) {
2214 raiseError(QXmlStreamReader::PrematureEndOfDocumentError);
2218 QString error_message;
2219 int ers = state_stack[tos];
2222 if (token != XML_ERROR)
2223 for (
int tk = 0; tk < TERMINAL_COUNT; ++tk) {
2224 int k = t_action(ers, tk);
2228 if (nexpected < nmax)
2229 expected[nexpected++] = tk;
2233 if (nexpected && nexpected < nmax) {
2235 QString exp_str = QXmlStream::tr(
"'%1'",
"expected")
2236 .arg(QLatin1StringView(spell[expected[0]]));
2237 if (nexpected == 2) {
2239 exp_str = QXmlStream::tr(
"%1 or '%2'",
"expected")
2240 .arg(exp_str, QLatin1StringView(spell[expected[1]]));
2241 }
else if (nexpected > 2) {
2243 for (; s < nexpected - 1; ++s) {
2245 exp_str = QXmlStream::tr(
"%1, '%2'",
"expected")
2246 .arg(exp_str, QLatin1StringView(spell[expected[s]]));
2249 exp_str = QXmlStream::tr(
"%1, or '%2'",
"expected")
2250 .arg(exp_str, QLatin1StringView(spell[expected[s]]));
2252 error_message = QXmlStream::tr(
"Expected %1, but got '%2'.")
2253 .arg(exp_str, QLatin1StringView(spell[token]));
2255 error_message = QXmlStream::tr(
"Unexpected '%1'.").arg(QLatin1StringView(spell[token]));
2258 raiseWellFormedError(error_message);
2261void QXmlStreamReaderPrivate::resume(
int rule) {
2262 resumeReduction = rule;
2263 if (error == QXmlStreamReader::NoError)
2264 raiseError(QXmlStreamReader::PrematureEndOfDocumentError);
2268
2269
2270
2271qint64 QXmlStreamReader::lineNumber()
const
2273 Q_D(
const QXmlStreamReader);
2274 return d->lineNumber + 1;
2278
2279
2280
2281qint64 QXmlStreamReader::columnNumber()
const
2283 Q_D(
const QXmlStreamReader);
2284 return d->characterOffset - d->lastLineStart + d->readBufferPos;
2288
2289
2290
2291qint64 QXmlStreamReader::characterOffset()
const
2293 Q_D(
const QXmlStreamReader);
2294 return d->characterOffset + d->readBufferPos;
2299
2300
2301QStringView QXmlStreamReader::text()
const
2303 Q_D(
const QXmlStreamReader);
2309
2310
2311
2312
2313
2314QXmlStreamNotationDeclarations QXmlStreamReader::notationDeclarations()
const
2316 Q_D(
const QXmlStreamReader);
2317 if (!d->scanDtd && !d->notationDeclarations.isEmpty())
2318 const_cast<QXmlStreamReaderPrivate *>(d)->resolveDtd();
2319 return d->publicNotationDeclarations;
2324
2325
2326
2327
2328
2329QXmlStreamEntityDeclarations QXmlStreamReader::entityDeclarations()
const
2331 Q_D(
const QXmlStreamReader);
2332 if (!d->scanDtd && !d->entityDeclarations.isEmpty())
2333 const_cast<QXmlStreamReaderPrivate *>(d)->resolveDtd();
2334 return d->publicEntityDeclarations;
2338
2339
2340
2341
2342
2343
2344QStringView QXmlStreamReader::dtdName()
const
2346 Q_D(
const QXmlStreamReader);
2347 if (d->type == QXmlStreamReader::DTD)
2349 return QStringView();
2353
2354
2355
2356
2357
2358
2359QStringView QXmlStreamReader::dtdPublicId()
const
2361 Q_D(
const QXmlStreamReader);
2362 if (d->type == QXmlStreamReader::DTD)
2363 return d->dtdPublicId;
2364 return QStringView();
2368
2369
2370
2371
2372
2373
2374QStringView QXmlStreamReader::dtdSystemId()
const
2376 Q_D(
const QXmlStreamReader);
2377 if (d->type == QXmlStreamReader::DTD)
2378 return d->dtdSystemId;
2379 return QStringView();
2383
2384
2385
2386
2387
2388
2389
2390
2391int QXmlStreamReader::entityExpansionLimit()
const
2393 Q_D(
const QXmlStreamReader);
2394 return d->entityExpansionLimit;
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414void QXmlStreamReader::setEntityExpansionLimit(
int limit)
2416 Q_D(QXmlStreamReader);
2418 qWarning(
"QXmlStreamReader::setEntityExpansionLimit(): "
2419 "limit %d is out of range [1:INT_MAX], clamping to 1.", limit);
2421 d->entityExpansionLimit = (std::max)(limit, 1);
2425
2426
2427
2428
2429
2430
2431
2432
2433QXmlStreamNamespaceDeclarations QXmlStreamReader::namespaceDeclarations()
const
2435 Q_D(
const QXmlStreamReader);
2436 if (d->publicNamespaceDeclarations.isEmpty() && d->type == StartElement)
2437 const_cast<QXmlStreamReaderPrivate *>(d)->resolvePublicNamespaces();
2438 return d->publicNamespaceDeclarations;
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452void QXmlStreamReader::addExtraNamespaceDeclaration(
const QXmlStreamNamespaceDeclaration &extraNamespaceDeclaration)
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());
2461
2462
2463
2464
2465
2466
2467void QXmlStreamReader::addExtraNamespaceDeclarations(
const QXmlStreamNamespaceDeclarations &extraNamespaceDeclarations)
2469 for (
const auto &extraNamespaceDeclaration : extraNamespaceDeclarations)
2470 addExtraNamespaceDeclaration(extraNamespaceDeclaration);
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491QString QXmlStreamReader::readElementText(ReadElementTextBehaviour behaviour)
2493 Q_D(QXmlStreamReader);
2494 if (isStartElement()) {
2496 qsizetype nestingLevel = 1;
2498 switch (readNext()) {
2500 case EntityReference:
2501 result.insert(result.size(), d->text);
2506 case ProcessingInstruction:
2510 if (behaviour == SkipChildElements) {
2511 skipCurrentElement();
2513 }
else if (behaviour == IncludeChildElements) {
2519 if (d->error || behaviour == ErrorOnUnexpectedElement) {
2521 d->raiseError(UnexpectedElementError, QXmlStream::tr(
"Expected character data."));
2525 }
while (nestingLevel);
2532
2533
2534
2535void QXmlStreamReader::raiseError(
const QString& message)
2537 Q_D(QXmlStreamReader);
2538 d->raiseError(CustomError, message);
2542
2543
2544
2545
2546QString QXmlStreamReader::errorString()
const
2548 Q_D(
const QXmlStreamReader);
2549 if (d->type == QXmlStreamReader::Invalid)
2550 return d->errorString;
2555
2556
2557
2558QXmlStreamReader::Error QXmlStreamReader::error()
const
2560 Q_D(
const QXmlStreamReader);
2561 if (d->type == QXmlStreamReader::Invalid)
2567
2568
2569QStringView QXmlStreamReader::processingInstructionTarget()
const
2571 Q_D(
const QXmlStreamReader);
2572 return d->processingInstructionTarget;
2576
2577
2578QStringView QXmlStreamReader::processingInstructionData()
const
2580 Q_D(
const QXmlStreamReader);
2581 return d->processingInstructionData;
2587
2588
2589
2590
2591QStringView QXmlStreamReader::name()
const
2593 Q_D(
const QXmlStreamReader);
2598
2599
2600
2601
2602QStringView QXmlStreamReader::namespaceUri()
const
2604 Q_D(
const QXmlStreamReader);
2605 return d->namespaceUri;
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620QStringView QXmlStreamReader::qualifiedName()
const
2622 Q_D(
const QXmlStreamReader);
2623 return d->qualifiedName;
2629
2630
2631
2632
2633
2634
2635QStringView QXmlStreamReader::prefix()
const
2637 Q_D(
const QXmlStreamReader);
2642
2643
2644QXmlStreamAttributes QXmlStreamReader::attributes()
const
2646 Q_D(
const QXmlStreamReader);
2647 return d->attributes;
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2670
2671
2672QXmlStreamAttribute::QXmlStreamAttribute()
2674 m_isDefault =
false;
2678
2679
2680
2681
2682QXmlStreamAttribute::QXmlStreamAttribute(
const QString &namespaceUri,
const QString &name,
const QString &value)
2683 : m_isDefault(
false)
2685 m_namespaceUri = namespaceUri;
2686 m_name = m_qualifiedName = name;
2691
2692
2693
2694
2695QXmlStreamAttribute::QXmlStreamAttribute(
const QString &qualifiedName,
const QString &value)
2696 : m_isDefault(
false)
2698 qsizetype colon = qualifiedName.indexOf(u':');
2699 m_name = qualifiedName.mid(colon + 1);
2700 m_qualifiedName = qualifiedName;
2705
2706
2707
2708
2710
2711
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2724
2725
2726
2727
2728
2729
2730
2733
2734
2737
2738
2739
2740
2741
2743
2744
2745
2746
2748
2749
2750
2751
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2776
2777
2778
2779
2782
2783
2784
2785
2786
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2804
2805
2806QXmlStreamNotationDeclaration::QXmlStreamNotationDeclaration()
2811
2812
2813
2815
2816
2817
2819
2820
2821
2824
2825
2826
2827
2829
2830
2831
2832
2835
2836
2837
2838
2839
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2855
2856
2857
2858
2860
2861
2862
2863
2866
2867
2868QXmlStreamNamespaceDeclaration::QXmlStreamNamespaceDeclaration()
2873
2874
2875
2876
2877QXmlStreamNamespaceDeclaration::QXmlStreamNamespaceDeclaration(
const QString &prefix,
const QString &namespaceUri)
2880 m_namespaceUri = namespaceUri;
2884
2885
2886
2888
2889
2890
2896
2897
2898
2899
2900
2903
2904
2905
2906
2907
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2924
2925
2926QXmlStreamEntityDeclaration::QXmlStreamEntityDeclaration()
2931
2932
2933
2935
2936
2937
2939
2940
2941
2943
2944
2945
2947
2948
2949
2952
2953
2954
2955
2957
2958
2959
2960
2963
2964
2965
2966
2967
2968
2969QStringView QXmlStreamAttributes::value(QAnyStringView namespaceUri, QAnyStringView name)
const noexcept
2971 for (
const QXmlStreamAttribute &attribute : *
this) {
2972 if (attribute.name() == name && attribute.namespaceUri() == namespaceUri)
2973 return attribute.value();
2975 return QStringView();
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994QStringView QXmlStreamAttributes::value(QAnyStringView qualifiedName)
const noexcept
2996 for (
const QXmlStreamAttribute &attribute : *
this) {
2997 if (attribute.qualifiedName() == qualifiedName)
2998 return attribute.value();
3000 return QStringView();
3004
3005
3006
3007void QXmlStreamAttributes::append(
const QString &namespaceUri,
const QString &name,
const QString &value)
3009 append(QXmlStreamAttribute(namespaceUri, name, value));
3013
3014
3015
3016void QXmlStreamAttributes::append(
const QString &qualifiedName,
const QString &value)
3018 append(QXmlStreamAttribute(qualifiedName, value));
3021#if QT_CONFIG(xmlstreamreader)
3024
3025
3027
3028
3030
3031
3033
3034
3036
3037
3038
3039
3041
3042
3044
3045
3047
3048
3050
3051
3054
3055
3056
3057
3058bool QXmlStreamReader::isWhitespace()
const
3060 Q_D(
const QXmlStreamReader);
3061 return d->type == QXmlStreamReader::Characters && d->isWhitespace;
3065
3066
3067
3068
3069bool QXmlStreamReader::isCDATA()
const
3071 Q_D(
const QXmlStreamReader);
3072 return d->type == QXmlStreamReader::Characters && d->isCDATA;
3078
3079
3080
3081
3082
3083
3084
3085bool QXmlStreamReader::isStandaloneDocument()
const
3087 Q_D(
const QXmlStreamReader);
3088 return d->standalone;
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101bool QXmlStreamReader::hasStandaloneDeclaration()
const
3103 Q_D(
const QXmlStreamReader);
3104 return d->hasStandalone;
3108
3109
3110
3111
3112
3113
3114QStringView QXmlStreamReader::documentVersion()
const
3116 Q_D(
const QXmlStreamReader);
3117 if (d->type == QXmlStreamReader::StartDocument)
3118 return d->documentVersion;
3119 return QStringView();
3123
3124
3125
3126
3127
3128
3129QStringView QXmlStreamReader::documentEncoding()
const
3131 Q_D(
const QXmlStreamReader);
3132 if (d->type == QXmlStreamReader::StartDocument)
3133 return d->documentEncoding;
3134 return QStringView();
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3255#if QT_CONFIG(xmlstreamwriter)
3257class QXmlStreamWriterPrivate :
public QXmlStreamPrivateTagStack
3259 QXmlStreamWriter *q_ptr;
3260 Q_DECLARE_PUBLIC(QXmlStreamWriter)
3262 enum class StartElementOption {
3264 OmitNamespaceDeclarations = 1,
3267 QXmlStreamWriterPrivate(QXmlStreamWriter *q);
3268 ~QXmlStreamWriterPrivate() {
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;
3297 NamespaceDeclaration &addExtraNamespace(QAnyStringView namespaceUri, QAnyStringView prefix);
3298 NamespaceDeclaration &findNamespace(QAnyStringView namespaceUri,
bool writeDeclaration =
false,
bool noDefault =
false);
3299 void writeNamespaceDeclaration(
const NamespaceDeclaration &namespaceDeclaration);
3301 int namespacePrefixCount = 0;
3303 void indent(
int level);
3305 void doWriteToDevice(QStringView s);
3306 void doWriteToDevice(QUtf8StringView s);
3307 void doWriteToDevice(QLatin1StringView s);
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)
3320void QXmlStreamWriterPrivate::raiseError(QXmlStreamWriter::Error errorCode)
3324 case QXmlStreamWriter::Error::IO:
3325 errorString = QXmlStream::tr(
"An I/O error occurred while writing");
3327 case QXmlStreamWriter::Error::Encoding:
3328 errorString = QXmlStream::tr(
"An encoding error occurred while writing");
3330 case QXmlStreamWriter::Error::InvalidCharacter:
3331 errorString = QXmlStream::tr(
"Encountered an invalid XML 1.0 character while writing");
3333 case QXmlStreamWriter::Error::Custom:
3334 errorString = QXmlStream::tr(
"An error occurred while writing");
3336 case QXmlStreamWriter::Error::None:
3337 errorString.clear();
3342void QXmlStreamWriterPrivate::raiseError(QXmlStreamWriter::Error errorCode, QAnyStringView message)
3345 errorString = message.toString();
3348void QXmlStreamWriterPrivate::write(QAnyStringView s)
3350 if (stopWritingOnError && (error != QXmlStreamWriter::Error::None))
3353 if (error == QXmlStreamWriter::Error::IO)
3356 s.visit([&] (
auto s) { doWriteToDevice(s); });
3357 }
else if (stringDevice) {
3358 s.visit([&] (
auto s) { stringDevice->append(s); });
3360 qWarning(
"QXmlStreamWriter: No device");
3364void QXmlStreamWriterPrivate::writeEscaped(QAnyStringView s,
bool escapeWhitespace)
3371 NextResult operator()(
const char *&it,
const char *)
const
3372 {
return {uchar(*it++),
false}; }
3375 NextResult operator()(
const char *&it,
const char *end)
const
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);
3386 return result == invalidValue ? NextResult{U'\0',
true}
3387 : NextResult{result,
false};
3391 NextResult operator()(
const QChar *&it,
const QChar *end)
const
3393 QStringIterator decoder(it, end);
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};
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>>;
3412 auto it = s.begin();
3413 const auto end = s.end();
3417 QLatin1StringView replacement;
3422 const auto decoded = decoder(next_it, end);
3423 switch (decoded.value) {
3425 replacement =
"<"_L1;
3428 replacement =
">"_L1;
3431 replacement =
"&"_L1;
3434 replacement =
"""_L1;
3437 if (escapeWhitespace)
3438 replacement =
"	"_L1;
3441 if (escapeWhitespace)
3442 replacement =
" "_L1;
3445 if (escapeWhitespace)
3446 replacement =
" "_L1;
3450 raiseError(QXmlStreamWriter::Error::InvalidCharacter);
3451 if (stopWritingOnError)
3453 replacement =
""_L1;
3454 Q_ASSERT(!replacement.isNull());
3457 if (decoded.value > 0x1F)
3463 raiseError(decoded.encodingError
3464 ? QXmlStreamWriter::Error::Encoding
3465 : QXmlStreamWriter::Error::InvalidCharacter);
3466 if (stopWritingOnError)
3468 replacement =
""_L1;
3469 Q_ASSERT(!replacement.isNull());
3472 if (!replacement.isNull())
3477 escaped.append(View{mark, it});
3478 escaped.append(replacement);
3487void QXmlStreamWriterPrivate::writeNamespaceDeclaration(
const NamespaceDeclaration &namespaceDeclaration) {
3488 if (namespaceDeclaration.prefix.isEmpty()) {
3490 write(namespaceDeclaration.namespaceUri);
3494 write(namespaceDeclaration.prefix);
3496 write(namespaceDeclaration.namespaceUri);
3499 didWriteAnyToken =
true;
3502bool QXmlStreamWriterPrivate::finishStartElement(
bool contents)
3504 bool hadSomethingWritten = wroteSomething;
3505 wroteSomething = contents;
3506 if (!inStartElement)
3507 return hadSomethingWritten;
3509 if (inEmptyElement) {
3511 QXmlStreamWriterPrivate::Tag tag = tagStack_pop();
3512 lastNamespaceDeclaration = tag.namespaceDeclarationsSize;
3513 lastWasStartElement =
false;
3517 inStartElement = inEmptyElement =
false;
3518 lastNamespaceDeclaration = namespaceDeclarations.size();
3519 didWriteAnyToken =
true;
3520 return hadSomethingWritten;
3523QXmlStreamPrivateTagStack::NamespaceDeclaration &
3524QXmlStreamWriterPrivate::addExtraNamespace(QAnyStringView namespaceUri, QAnyStringView prefix)
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));
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));
3543 auto &namespaceDeclaration = namespaceDeclarations.push();
3544 namespaceDeclaration.prefix = addToStringStorage(prefix);
3545 namespaceDeclaration.namespaceUri = addToStringStorage(namespaceUri);
3546 return namespaceDeclaration;
3549QXmlStreamPrivateTagStack::NamespaceDeclaration &QXmlStreamWriterPrivate::findNamespace(QAnyStringView namespaceUri,
bool writeDeclaration,
bool noDefault)
3551 for (NamespaceDeclaration &namespaceDeclaration : reversed(namespaceDeclarations)) {
3552 if (namespaceDeclaration.namespaceUri == namespaceUri) {
3553 if (!noDefault || !namespaceDeclaration.prefix.isEmpty())
3554 return namespaceDeclaration;
3557 if (namespaceUri.isEmpty())
3558 return emptyNamespace;
3559 NamespaceDeclaration &namespaceDeclaration = namespaceDeclarations.push();
3560 if (namespaceUri.isEmpty()) {
3561 namespaceDeclaration.prefix.clear();
3564 int n = ++namespacePrefixCount;
3566 s = u'n' + QString::number(n++);
3567 qsizetype j = namespaceDeclarations.size() - 2;
3568 while (j >= 0 && namespaceDeclarations.at(j).prefix != s)
3573 namespaceDeclaration.prefix = addToStringStorage(s);
3575 namespaceDeclaration.namespaceUri = addToStringStorage(namespaceUri);
3576 if (writeDeclaration)
3577 writeNamespaceDeclaration(namespaceDeclaration);
3578 return namespaceDeclaration;
3583void QXmlStreamWriterPrivate::indent(
int level)
3585 if (didWriteStartDocument || didWriteAnyToken)
3587 for (
int i = 0; i < level; ++i)
3588 write(autoFormattingIndent);
3591void QXmlStreamWriterPrivate::doWriteToDevice(QStringView s)
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);
3602 if (state.remainingChars > 0)
3603 raiseError(QXmlStreamWriter::Error::Encoding);
3606void QXmlStreamWriterPrivate::doWriteToDevice(QUtf8StringView s)
3608 QByteArrayView bytes = s;
3609 if (device->write(bytes.data(), bytes.size()) != bytes.size())
3610 raiseError(QXmlStreamWriter::Error::IO);
3613void QXmlStreamWriterPrivate::doWriteToDevice(QLatin1StringView s)
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);
3626
3627
3628
3629
3630QXmlStreamWriter::QXmlStreamWriter()
3631 : d_ptr(
new QXmlStreamWriterPrivate(
this))
3636
3637
3638QXmlStreamWriter::QXmlStreamWriter(QIODevice *device)
3639 : d_ptr(
new QXmlStreamWriterPrivate(
this))
3641 Q_D(QXmlStreamWriter);
3646
3647
3648
3649QXmlStreamWriter::QXmlStreamWriter(QByteArray *array)
3650 : d_ptr(
new QXmlStreamWriterPrivate(
this))
3652 Q_D(QXmlStreamWriter);
3653 d->device =
new QBuffer(array);
3654 d->device->open(QIODevice::WriteOnly);
3655 d->deleteDevice =
true;
3660
3661QXmlStreamWriter::QXmlStreamWriter(QString *string)
3662 : d_ptr(
new QXmlStreamWriterPrivate(
this))
3664 Q_D(QXmlStreamWriter);
3665 d->stringDevice = string;
3669
3670
3671QXmlStreamWriter::~QXmlStreamWriter()
3677
3678
3679
3680
3681
3682void QXmlStreamWriter::setDevice(QIODevice *device)
3684 Q_D(QXmlStreamWriter);
3685 if (device == d->device)
3687 d->stringDevice =
nullptr;
3688 if (d->deleteDevice) {
3690 d->deleteDevice =
false;
3696
3697
3698
3699
3700
3701QIODevice *QXmlStreamWriter::device()
const
3703 Q_D(
const QXmlStreamWriter);
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3724
3725
3726
3727
3728
3729
3730
3731void QXmlStreamWriter::setAutoFormatting(
bool enable)
3733 Q_D(QXmlStreamWriter);
3734 d->autoFormatting = enable;
3738
3739
3740
3741
3742bool QXmlStreamWriter::autoFormatting()
const
3744 Q_D(
const QXmlStreamWriter);
3745 return d->autoFormatting;
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3762void QXmlStreamWriter::setAutoFormattingIndent(
int spacesOrTabs)
3764 Q_D(QXmlStreamWriter);
3765 d->autoFormattingIndent.assign(size_t(qAbs(spacesOrTabs)), spacesOrTabs >= 0 ?
' ' :
'\t');
3768int QXmlStreamWriter::autoFormattingIndent()
const
3770 Q_D(
const QXmlStreamWriter);
3771 const QLatin1StringView indent(d->autoFormattingIndent);
3772 return indent.count(u' ') - indent.count(u'\t');
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792bool QXmlStreamWriter::stopWritingOnError()
const
3794 Q_D(
const QXmlStreamWriter);
3795 return d->stopWritingOnError;
3798void QXmlStreamWriter::setStopWritingOnError(
bool stop)
3800 Q_D(QXmlStreamWriter);
3801 d->stopWritingOnError = stop;
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816bool QXmlStreamWriter::hasError()
const
3818 return error() != QXmlStreamWriter::Error::None;
3822
3823
3824
3825
3826
3827
3828
3829
3830QXmlStreamWriter::Error QXmlStreamWriter::error()
const
3832 Q_D(
const QXmlStreamWriter);
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846QString QXmlStreamWriter::errorString()
const
3848 Q_D(
const QXmlStreamWriter);
3849 return d->errorString;
3853
3854
3855
3856
3857
3858
3859
3860
3861void QXmlStreamWriter::raiseError(QAnyStringView message)
3863 Q_D(QXmlStreamWriter);
3864 d->raiseError(QXmlStreamWriter::Error::Custom, message);
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878void QXmlStreamWriter::writeAttribute(QAnyStringView qualifiedName, QAnyStringView value)
3880 Q_D(QXmlStreamWriter);
3881 Q_ASSERT(d->inStartElement);
3882 Q_ASSERT(count(qualifiedName,
':') <= 1);
3884 d->write(qualifiedName);
3886 d->writeEscaped(value,
true);
3888 d->didWriteAnyToken =
true;
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902void QXmlStreamWriter::writeAttribute(QAnyStringView namespaceUri, QAnyStringView name, QAnyStringView value)
3904 Q_D(QXmlStreamWriter);
3905 Q_ASSERT(d->inStartElement);
3906 Q_ASSERT(!contains(name,
':'));
3907 QXmlStreamWriterPrivate::NamespaceDeclaration &namespaceDeclaration = d->findNamespace(namespaceUri,
true,
true);
3909 if (!namespaceDeclaration.prefix.isEmpty()) {
3910 d->write(namespaceDeclaration.prefix);
3915 d->writeEscaped(value,
true);
3917 d->didWriteAnyToken =
true;
3921
3922
3923
3924
3925
3926
3927
3928void QXmlStreamWriter::writeAttribute(
const QXmlStreamAttribute& attribute)
3930 if (attribute.namespaceUri().isEmpty())
3931 writeAttribute(attribute.qualifiedName(), attribute.value());
3933 writeAttribute(attribute.namespaceUri(), attribute.name(), attribute.value());
3938
3939
3940
3941
3942
3943
3944
3945
3946void QXmlStreamWriter::writeAttributes(
const QXmlStreamAttributes& attributes)
3948 Q_D(QXmlStreamWriter);
3949 Q_ASSERT(d->inStartElement);
3951 for (
const auto &attr : attributes)
3952 writeAttribute(attr);
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967void QXmlStreamWriter::writeCDATA(QAnyStringView text)
3969 Q_D(QXmlStreamWriter);
3970 d->finishStartElement();
3971 d->write(
"<![CDATA[");
3972 while (!text.isEmpty()) {
3973 const auto idx = indexOf(text,
"]]>"_L1);
3976 d->write(text.first(idx));
3980 text = text.sliced(idx + 3);
3988
3989
3990
3991
3992
3993
3994
3995
3996void QXmlStreamWriter::writeCharacters(QAnyStringView text)
3998 Q_D(QXmlStreamWriter);
3999 d->finishStartElement();
4000 d->writeEscaped(text);
4005
4006
4007
4008
4009
4010
4011void QXmlStreamWriter::writeComment(QAnyStringView text)
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());
4020 d->inStartElement = d->lastWasStartElement =
false;
4025
4026
4027
4028
4029
4030void QXmlStreamWriter::writeDTD(QAnyStringView dtd)
4032 Q_D(QXmlStreamWriter);
4033 d->finishStartElement();
4034 if (d->autoFormatting)
4037 if (d->autoFormatting)
4044
4045
4046
4047
4048
4049
4050void QXmlStreamWriter::writeEmptyElement(QAnyStringView qualifiedName)
4052 Q_D(QXmlStreamWriter);
4053 Q_ASSERT(count(qualifiedName,
':') <= 1);
4054 d->writeStartElement({}, qualifiedName);
4055 d->inEmptyElement =
true;
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069void QXmlStreamWriter::writeEmptyElement(QAnyStringView namespaceUri, QAnyStringView name)
4071 Q_D(QXmlStreamWriter);
4072 Q_ASSERT(!contains(name,
':'));
4073 d->writeStartElement(namespaceUri, name);
4074 d->inEmptyElement =
true;
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088void QXmlStreamWriter::writeTextElement(QAnyStringView qualifiedName, QAnyStringView text)
4090 writeStartElement(qualifiedName);
4091 writeCharacters(text);
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107void QXmlStreamWriter::writeTextElement(QAnyStringView namespaceUri, QAnyStringView name, QAnyStringView text)
4109 writeStartElement(namespaceUri, name);
4110 writeCharacters(text);
4116
4117
4118
4119
4120void QXmlStreamWriter::writeEndDocument()
4122 Q_D(QXmlStreamWriter);
4123 while (d->tagStack.size())
4125 if (d->didWriteStartDocument || d->didWriteAnyToken)
4130
4131
4132
4133
4134void QXmlStreamWriter::writeEndElement()
4136 Q_D(QXmlStreamWriter);
4137 Q_ASSERT(d->didWriteAnyToken);
4138 if (d->tagStack.isEmpty())
4142 if (d->inStartElement && !d->inEmptyElement) {
4144 d->lastWasStartElement = d->inStartElement =
false;
4145 QXmlStreamWriterPrivate::Tag tag = d->tagStack_pop();
4146 d->lastNamespaceDeclaration = tag.namespaceDeclarationsSize;
4150 if (!d->finishStartElement(
false) && !d->lastWasStartElement && d->autoFormatting)
4151 d->indent(d->tagStack.size()-1);
4152 if (d->tagStack.isEmpty())
4154 d->lastWasStartElement =
false;
4155 QXmlStreamWriterPrivate::Tag tag = d->tagStack_pop();
4156 d->lastNamespaceDeclaration = tag.namespaceDeclarationsSize;
4158 if (!tag.namespaceDeclaration.prefix.isEmpty()) {
4159 d->write(tag.namespaceDeclaration.prefix);
4169
4170
4171
4172
4173
4174void QXmlStreamWriter::writeEntityReference(QAnyStringView name)
4176 Q_D(QXmlStreamWriter);
4177 d->finishStartElement();
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201void QXmlStreamWriter::writeNamespace(QAnyStringView namespaceUri, QAnyStringView prefix)
4203 Q_D(QXmlStreamWriter);
4204 Q_ASSERT(prefix !=
"xmlns"_L1);
4205 if (prefix.isEmpty()) {
4206 d->findNamespace(namespaceUri, d->inStartElement);
4208 auto &namespaceDeclaration = d->addExtraNamespace(namespaceUri, prefix);
4209 if (d->inStartElement)
4210 d->writeNamespaceDeclaration(namespaceDeclaration);
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228void QXmlStreamWriter::writeDefaultNamespace(QAnyStringView namespaceUri)
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);
4242
4243
4244
4245
4246
4247
4248void QXmlStreamWriter::writeProcessingInstruction(QAnyStringView target, QAnyStringView data)
4250 Q_D(QXmlStreamWriter);
4251 Q_ASSERT(!contains(data,
"?>"_L1));
4252 if (!d->finishStartElement(
false) && d->autoFormatting)
4253 d->indent(d->tagStack.size());
4256 if (!data.isNull()) {
4261 d->didWriteAnyToken =
true;
4267
4268
4269
4270
4271
4272
4273void QXmlStreamWriter::writeStartDocument()
4275 writeStartDocument(
"1.0"_L1);
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295void QXmlStreamWriter::writeStartDocument(QAnyStringView version)
4297 Q_D(QXmlStreamWriter);
4298 d->finishStartElement(
false);
4299 d->write(
"<?xml version=\"");
4302 d->write(
"\" encoding=\"UTF-8");
4304 d->didWriteStartDocument =
true;
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325void QXmlStreamWriter::writeStartDocument(QAnyStringView version,
bool standalone)
4327 Q_D(QXmlStreamWriter);
4328 d->finishStartElement(
false);
4329 d->write(
"<?xml version=\"");
4332 d->write(
"\" encoding=\"UTF-8");
4334 d->write(
"\" standalone=\"yes\"?>");
4336 d->write(
"\" standalone=\"no\"?>");
4337 d->didWriteStartDocument =
true;
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351void QXmlStreamWriter::writeStartElement(QAnyStringView qualifiedName)
4353 Q_D(QXmlStreamWriter);
4354 Q_ASSERT(count(qualifiedName,
':') <= 1);
4355 d->writeStartElement({}, qualifiedName);
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370void QXmlStreamWriter::writeStartElement(QAnyStringView namespaceUri, QAnyStringView name)
4372 Q_D(QXmlStreamWriter);
4373 Q_ASSERT(!contains(name,
':'));
4374 d->writeStartElement(namespaceUri, name);
4377void QXmlStreamWriterPrivate::writeStartElement(QAnyStringView namespaceUri, QAnyStringView name,
4378 StartElementOption option)
4380 if (!finishStartElement(
false) && autoFormatting)
4381 indent(tagStack.size());
4383 Tag &tag = tagStack_push();
4384 tag.name = addToStringStorage(name);
4385 tag.namespaceDeclaration = findNamespace(namespaceUri);
4387 if (!tag.namespaceDeclaration.prefix.isEmpty()) {
4388 write(tag.namespaceDeclaration.prefix);
4392 inStartElement = lastWasStartElement =
true;
4394 if (option != StartElementOption::OmitNamespaceDeclarations) {
4395 for (qsizetype i = lastNamespaceDeclaration; i < namespaceDeclarations.size(); ++i)
4396 writeNamespaceDeclaration(namespaceDeclarations[i]);
4398 tag.namespaceDeclarationsSize = lastNamespaceDeclaration;
4399 didWriteAnyToken =
true;
4402#if QT_CONFIG(xmlstreamreader)
4404
4405
4406
4407
4408
4409
4410void QXmlStreamWriter::writeCurrentToken(
const QXmlStreamReader &reader)
4412 Q_D(QXmlStreamWriter);
4413 switch (reader.tokenType()) {
4414 case QXmlStreamReader::NoToken:
4416 case QXmlStreamReader::StartDocument:
4417 writeStartDocument();
4419 case QXmlStreamReader::EndDocument:
4422 case QXmlStreamReader::StartElement: {
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);
4431 d->writeStartElement(
4432 reader.namespaceUri(), reader.name(),
4433 QXmlStreamWriterPrivate::StartElementOption::OmitNamespaceDeclarations);
4435 for (
const auto &extraNamespace : std::as_const(extraNamespaces))
4436 d->writeNamespaceDeclaration(extraNamespace);
4437 writeAttributes(reader.attributes());
4439 case QXmlStreamReader::EndElement:
4442 case QXmlStreamReader::Characters:
4443 if (reader.isCDATA())
4444 writeCDATA(reader.text());
4446 writeCharacters(reader.text());
4448 case QXmlStreamReader::Comment:
4449 writeComment(reader.text());
4451 case QXmlStreamReader::DTD:
4452 writeDTD(reader.text());
4454 case QXmlStreamReader::EntityReference:
4455 writeEntityReference(reader.name());
4457 case QXmlStreamReader::ProcessingInstruction:
4458 writeProcessingInstruction(reader.processingInstructionTarget(),
4459 reader.processingInstructionData());
4462 Q_ASSERT(reader.tokenType() != QXmlStreamReader::Invalid);
4463 qWarning(
"QXmlStreamWriter: writeCurrentToken() with invalid state.");
4470#if QT_CONFIG(xmlstreamreader)
4471static constexpr bool isTokenAllowedInContext(QXmlStreamReader::TokenType type,
4472 QXmlStreamReaderPrivate::XmlContext ctxt)
4475 case QXmlStreamReader::StartDocument:
4476 case QXmlStreamReader::DTD:
4477 return ctxt == QXmlStreamReaderPrivate::XmlContext::Prolog;
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;
4486 case QXmlStreamReader::Comment:
4487 case QXmlStreamReader::ProcessingInstruction:
4490 case QXmlStreamReader::NoToken:
4491 case QXmlStreamReader::Invalid:
4496#if !defined(Q_CC_GNU_ONLY) || (Q_CC_GNU >= 900
)
4497 Q_UNREACHABLE_RETURN(
false);
4504
4505
4506
4507
4508
4509
4510bool QXmlStreamReaderPrivate::isValidToken(QXmlStreamReader::TokenType type)
4513 if (type == QXmlStreamReader::Invalid || type == QXmlStreamReader::NoToken)
4517 const bool result = isTokenAllowedInContext(type, currentContext);
4518 if (result || currentContext == XmlContext::Body)
4522 currentContext = XmlContext::Body;
4523 return isTokenAllowedInContext(type, currentContext);
4527
4528
4529
4530
4531void QXmlStreamReaderPrivate::checkToken()
4533 Q_Q(QXmlStreamReader);
4536 const XmlContext context = currentContext;
4537 const bool ok = isValidToken(type);
4540 if (error != QXmlStreamReader::Error::NoError)
4544 raiseError(QXmlStreamReader::UnexpectedElementError,
4545 QXmlStream::tr(
"Unexpected token type %1 in %2.")
4546 .arg(q->tokenString(), contextString(context)));
4550 if (type != QXmlStreamReader::DTD)
4555 raiseError(QXmlStreamReader::UnexpectedElementError,
4556 QXmlStream::tr(
"Found second DTD token in %1.").arg(contextString(context)));
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4577
4578
4579
4580
4581
4582
4583
4584