1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
|
//------------------------------------------------------------------------------
// <copyright file="XmlConvert.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml {
using System.IO;
using System.Text;
using System.Globalization;
using System.Xml.Schema;
using System.Diagnostics;
using System.Collections;
using System.Text.RegularExpressions;
// ExceptionType enum is used inside XmlConvert to specify which type of exception should be thrown at some of the verification and exception creating methods
internal enum ExceptionType {
ArgumentException,
XmlException,
}
// Options for serializing and deserializing DateTime
public enum XmlDateTimeSerializationMode {
Local,
Utc,
Unspecified,
RoundtripKind,
}
/// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert"]/*' />
/// <devdoc>
/// Encodes and decodes XML names according to
/// the "Encoding of arbitrary Unicode Characters in XML Names" specification.
/// </devdoc>
public class XmlConvert {
//
// Static fields with implicit initialization
//
static XmlCharType xmlCharType = XmlCharType.Instance;
#if !SILVERLIGHT
internal static char[] crt = new char[] {'\n', '\r', '\t'};
#endif
/// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeName"]/*' />
/// <devdoc>
/// <para>
/// Converts names, such
/// as DataTable or
/// DataColumn names, that contain characters that are not permitted in
/// XML names to valid names.</para>
/// </devdoc>
public static string EncodeName(string name) {
return EncodeName(name, true/*Name_not_NmToken*/, false/*Local?*/);
}
/// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeNmToken"]/*' />
/// <devdoc>
/// <para> Verifies the name is valid
/// according to production [7] in the XML spec.</para>
/// </devdoc>
public static string EncodeNmToken(string name) {
return EncodeName(name, false/*Name_not_NmToken*/, false/*Local?*/);
}
/// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeLocalName"]/*' />
/// <devdoc>
/// <para>Converts names, such as DataTable or DataColumn names, that contain
/// characters that are not permitted in XML names to valid names.</para>
/// </devdoc>
public static string EncodeLocalName(string name) {
return EncodeName(name, true/*Name_not_NmToken*/, true/*Local?*/);
}
/// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.DecodeName"]/*' />
/// <devdoc>
/// <para>
/// Transforms an XML name into an object name (such as DataTable or DataColumn).</para>
/// </devdoc>
public static string DecodeName(string name) {
if (name == null || name.Length == 0)
return name;
StringBuilder bufBld = null;
int length = name.Length;
int copyPosition = 0;
int underscorePos = name.IndexOf('_');
MatchCollection mc = null;
IEnumerator en = null;
if (underscorePos >= 0)
{
if ( c_DecodeCharPattern == null ) {
c_DecodeCharPattern = new Regex("_[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_");
}
mc = c_DecodeCharPattern.Matches(name, underscorePos);
en = mc.GetEnumerator();
} else {
return name;
}
int matchPos = -1;
if (en != null && en.MoveNext())
{
Match m = (Match)en.Current;
matchPos = m.Index;
}
for (int position = 0; position < length - c_EncodedCharLength + 1; position ++) {
if (position == matchPos) {
if (en.MoveNext())
{
Match m = (Match)en.Current;
matchPos = m.Index;
}
if (bufBld == null) {
bufBld = new StringBuilder(length + 20);
}
bufBld.Append(name, copyPosition, position - copyPosition);
if (name[position + 6]!='_') { //_x1234_
Int32 u =
FromHex(name[position + 2]) * 0x10000000 +
FromHex(name[position + 3]) * 0x1000000 +
FromHex(name[position + 4]) * 0x100000 +
FromHex(name[position + 5]) * 0x10000 +
FromHex(name[position + 6]) * 0x1000 +
FromHex(name[position + 7]) * 0x100 +
FromHex(name[position + 8]) * 0x10 +
FromHex(name[position + 9]);
if (u >= 0x00010000) {
if (u <= 0x0010ffff) { //convert to two chars
copyPosition = position + c_EncodedCharLength + 4;
char lowChar, highChar;
XmlCharType.SplitSurrogateChar(u, out lowChar, out highChar);
bufBld.Append(highChar);
bufBld.Append(lowChar);
}
//else bad ucs-4 char dont convert
}
else { //convert to single char
copyPosition = position + c_EncodedCharLength + 4;
bufBld.Append((char)u);
}
position += c_EncodedCharLength - 1 + 4; //just skip
}
else {
copyPosition = position + c_EncodedCharLength;
bufBld.Append((char)(
FromHex(name[position + 2]) * 0x1000 +
FromHex(name[position + 3]) * 0x100 +
FromHex(name[position + 4]) * 0x10 +
FromHex(name[position + 5])));
position += c_EncodedCharLength - 1;
}
}
}
if (copyPosition == 0) {
return name;
}
else {
if (copyPosition < length) {
bufBld.Append(name, copyPosition, length - copyPosition);
}
return bufBld.ToString();
}
}
private static string EncodeName(string name, /*Name_not_NmToken*/ bool first, bool local) {
if (string.IsNullOrEmpty(name)) {
return name;
}
StringBuilder bufBld = null;
int length = name.Length;
int copyPosition = 0;
int position = 0;
int underscorePos = name.IndexOf('_');
MatchCollection mc = null;
IEnumerator en = null;
if (underscorePos >= 0)
{
if ( c_EncodeCharPattern == null ) {
c_EncodeCharPattern = new Regex("(?<=_)[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_");
}
mc = c_EncodeCharPattern.Matches(name, underscorePos);
en = mc.GetEnumerator();
}
int matchPos = -1;
if (en != null && en.MoveNext())
{
Match m = (Match)en.Current;
matchPos = m.Index - 1;
}
if (first) {
if ( ( !xmlCharType.IsStartNCNameCharXml4e( name[0] ) && (local || (!local && name[0] != ':'))) ||
matchPos == 0) {
if (bufBld == null) {
bufBld = new StringBuilder(length + 20);
}
bufBld.Append("_x");
if (length > 1 && XmlCharType.IsHighSurrogate(name[0]) && XmlCharType.IsLowSurrogate(name[1]) ) {
int x = name[0];
int y = name[1];
Int32 u = XmlCharType.CombineSurrogateChar(y, x);
bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture));
position ++;
copyPosition = 2;
}
else {
bufBld.Append(((Int32)name[0]).ToString("X4", CultureInfo.InvariantCulture));
copyPosition = 1;
}
bufBld.Append("_");
position ++;
if (matchPos == 0)
if (en.MoveNext())
{
Match m = (Match)en.Current;
matchPos = m.Index - 1;
}
}
}
for (; position < length; position ++) {
if ((local && !xmlCharType.IsNCNameCharXml4e(name[position])) ||
(!local && !xmlCharType.IsNameCharXml4e(name[position])) ||
(matchPos == position))
{
if (bufBld == null) {
bufBld = new StringBuilder(length + 20);
}
if (matchPos == position)
if (en.MoveNext())
{
Match m = (Match)en.Current;
matchPos = m.Index - 1;
}
bufBld.Append(name, copyPosition, position - copyPosition);
bufBld.Append("_x");
if ((length > position + 1) && XmlCharType.IsHighSurrogate(name[position]) && XmlCharType.IsLowSurrogate(name[position + 1])) {
int x = name[position];
int y = name[position + 1];
Int32 u = XmlCharType.CombineSurrogateChar(y, x);
bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture));
copyPosition = position + 2;
position ++;
}
else {
bufBld.Append(((Int32)name[position]).ToString("X4", CultureInfo.InvariantCulture));
copyPosition = position + 1;
}
bufBld.Append("_");
}
}
if (copyPosition == 0) {
return name;
}
else {
if (copyPosition < length) {
bufBld.Append(name, copyPosition, length - copyPosition);
}
return bufBld.ToString();
}
}
private static readonly int c_EncodedCharLength = 7; // ("_xFFFF_".Length);
private static volatile Regex c_EncodeCharPattern;
private static volatile Regex c_DecodeCharPattern;
private static int FromHex(char digit) {
return(digit <= '9')
? ((int)digit - (int)'0')
: (((digit <= 'F')
? ((int)digit - (int)'A')
: ((int)digit - (int)'a'))
+ 10);
}
internal static byte[] FromBinHexString(string s) {
return FromBinHexString(s, true);
}
internal static byte[] FromBinHexString(string s, bool allowOddCount ) {
if (s == null) {
throw new ArgumentNullException("s");
}
return BinHexDecoder.Decode(s.ToCharArray(), allowOddCount);
}
internal static string ToBinHexString(byte[] inArray) {
if (inArray == null) {
throw new ArgumentNullException("inArray");
}
return BinHexEncoder.Encode(inArray, 0, inArray.Length);
}
//
// Verification methods for strings
//
/// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyName"]/*' />
/// <devdoc>
/// <para>
/// </para>
/// </devdoc>
public static string VerifyName(string name) {
if (name == null) {
throw new ArgumentNullException("name");
}
if (name.Length == 0) {
throw new ArgumentNullException("name", Res.GetString(Res.Xml_EmptyName));
}
// parse name
int endPos = ValidateNames.ParseNameNoNamespaces(name, 0);
if (endPos != name.Length) {
// did not parse to the end -> there is invalid character at endPos
throw CreateInvalidNameCharException(name, endPos, ExceptionType.XmlException);
}
return name;
}
#if !SILVERLIGHT
internal static Exception TryVerifyName(string name) {
if (name == null || name.Length == 0) {
return new XmlException(Res.Xml_EmptyName, string.Empty);
}
int endPos = ValidateNames.ParseNameNoNamespaces(name, 0);
if (endPos != name.Length) {
return new XmlException(endPos == 0 ? Res.Xml_BadStartNameChar : Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos));
}
return null;
}
internal static string VerifyQName(string name) {
return VerifyQName(name, ExceptionType.XmlException);
}
#endif
#if SILVERLIGHT
internal static string VerifyQName(string name, ExceptionType exceptionType) {
#else
internal static unsafe string VerifyQName(string name, ExceptionType exceptionType) {
#endif
if (name == null || name.Length == 0) {
throw new ArgumentNullException("name");
}
int colonPosition = -1;
int endPos = ValidateNames.ParseQName(name, 0, out colonPosition);
if (endPos != name.Length) {
throw CreateException(Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1);
}
return name;
}
/// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyNCName"]/*' />
/// <devdoc>
/// <para>
/// </para>
/// </devdoc>
public static string VerifyNCName(string name) {
return VerifyNCName(name, ExceptionType.XmlException);
}
internal static string VerifyNCName(string name, ExceptionType exceptionType) {
if (name == null) {
throw new ArgumentNullException("name");
}
if (name.Length == 0) {
throw new ArgumentNullException("name", Res.GetString(Res.Xml_EmptyLocalName));
}
int end = ValidateNames.ParseNCName(name, 0);
if (end != name.Length) {
// If the string is not a valid NCName, then throw or return false
throw CreateInvalidNameCharException(name, end, exceptionType);
}
return name;
}
#if !SILVERLIGHT
internal static Exception TryVerifyNCName(string name) {
int len = ValidateNames.ParseNCName(name);
if (len == 0 || len != name.Length) {
return ValidateNames.GetInvalidNameException(name, 0, len);
}
return null;
}
/// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyTOKEN"]/*' />
/// <devdoc>
/// <para>
/// </para>
/// </devdoc>
public static string VerifyTOKEN(string token) {
if (token == null || token.Length == 0) {
return token;
}
if (token[0] == ' ' || token[token.Length - 1] == ' ' || token.IndexOfAny(crt) != -1 || token.IndexOf(" ", StringComparison.Ordinal) != -1) {
throw new XmlException(Res.Sch_NotTokenString, token);
}
return token;
}
internal static Exception TryVerifyTOKEN(string token) {
if (token == null || token.Length == 0) {
return null;
}
if (token[0] == ' ' || token[token.Length - 1] == ' ' || token.IndexOfAny(crt) != -1 || token.IndexOf(" ", StringComparison.Ordinal) != -1) {
return new XmlException(Res.Sch_NotTokenString, token);
}
return null;
}
#endif
/// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyNMTOKEN"]/*' />
/// <devdoc>
/// <para>
/// </para>
/// </devdoc>
public static string VerifyNMTOKEN(string name) {
return VerifyNMTOKEN(name, ExceptionType.XmlException);
}
internal static string VerifyNMTOKEN(string name, ExceptionType exceptionType) {
if (name == null) {
throw new ArgumentNullException("name");
}
if (name.Length == 0) {
throw CreateException(Res.Xml_InvalidNmToken, name, exceptionType);
}
int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0);
if (endPos != name.Length) {
throw CreateException(Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1);
}
return name;
}
#if !SILVERLIGHT
internal static Exception TryVerifyNMTOKEN(string name) {
if (name == null || name.Length == 0) {
return new XmlException(Res.Xml_EmptyName, string.Empty);
}
int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0);
if (endPos != name.Length) {
return new XmlException(Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos));
}
return null;
}
internal static string VerifyNormalizedString(string str) {
if (str.IndexOfAny(crt) != -1) {
throw new XmlSchemaException(Res.Sch_NotNormalizedString, str);
}
return str;
}
internal static Exception TryVerifyNormalizedString(string str) {
if (str.IndexOfAny(crt) != -1) {
return new XmlSchemaException(Res.Sch_NotNormalizedString, str);
}
return null;
}
#endif
// Verification method for XML characters as defined in XML spec production [2] Char.
// Throws XmlException if invalid character is found, otherwise returns the input string.
public static string VerifyXmlChars(string content) {
if (content == null) {
throw new ArgumentNullException("content");
}
VerifyCharData(content, ExceptionType.XmlException);
return content;
}
// Verification method for XML public ID characters as defined in XML spec production [13] PubidChar.
// Throws XmlException if invalid character is found, otherwise returns the input string.
public static string VerifyPublicId(string publicId) {
if (publicId == null) {
throw new ArgumentNullException("publicId");
}
// returns the position of invalid character or -1
int pos = xmlCharType.IsPublicId(publicId);
if (pos != -1) {
throw CreateInvalidCharException(publicId, pos, ExceptionType.XmlException);
}
return publicId;
}
// Verification method for XML whitespace characters as defined in XML spec production [3] S.
// Throws XmlException if invalid character is found, otherwise returns the input string.
public static string VerifyWhitespace(string content) {
if (content == null) {
throw new ArgumentNullException("content");
}
// returns the position of invalid character or -1
int pos = xmlCharType.IsOnlyWhitespaceWithPos(content);
if (pos != -1) {
throw new XmlException(Res.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(content, pos), 0, pos + 1);
}
return content;
}
//
// Verification methods for single characters and surrogates
//
// In cases where the direct call into XmlCharType would not get automatically inlined (because of the use of byte* field),
// direct access to the XmlCharType.charProperties is used instead (= manual inlining).
//
// Start name character types - as defined in Namespaces XML 1.0 spec (second edition) production [6] NCNameStartChar
// combined with the production [4] NameStartChar of XML 1.0 spec
public static unsafe bool IsStartNCNameChar(char ch) {
#if SILVERLIGHT
return xmlCharType.IsStartNCNameSingleChar(ch);
#else
return (xmlCharType.charProperties[ch] & XmlCharType.fNCStartNameSC) != 0;
#endif
}
#if XML10_FIFTH_EDITION
public static bool IsStartNCNameSurrogatePair(char lowChar, char highChar) {
return xmlCharType.IsNCNameSurrogateChar(lowChar, highChar);
}
#endif
// Name character types - as defined in Namespaces XML 1.0 spec (second edition) production [6] NCNameStartChar
// combined with the production [4] NameChar of XML 1.0 spec
public static unsafe bool IsNCNameChar(char ch) {
#if SILVERLIGHT
return xmlCharType.IsNCNameSingleChar(ch);
#else
return (xmlCharType.charProperties[ch] & XmlCharType.fNCNameSC) != 0;
#endif
}
#if XML10_FIFTH_EDITION
public static bool IsNCNameSurrogatePair(char lowChar, char highChar) {
return xmlCharType.IsNCNameSurrogateChar(lowChar, highChar);
}
#endif
// Valid XML character – as defined in XML 1.0 spec (fifth edition) production [2] Char
public static unsafe bool IsXmlChar(char ch) {
#if SILVERLIGHT
return xmlCharType.IsCharData(ch);
#else
return (xmlCharType.charProperties[ch] & XmlCharType.fCharData) != 0;
#endif
}
public static bool IsXmlSurrogatePair(char lowChar, char highChar) {
return XmlCharType.IsHighSurrogate(highChar) && XmlCharType.IsLowSurrogate(lowChar);
}
// Valid PUBLIC ID character – as defined in XML 1.0 spec (fifth edition) production [13] PublidChar
public static bool IsPublicIdChar(char ch) {
return xmlCharType.IsPubidChar(ch);
}
// Valid Xml white space – as defined in XML 1.0 spec (fifth edition) production [3] S
public static unsafe bool IsWhitespaceChar(char ch) {
#if SILVERLIGHT
return xmlCharType.IsWhiteSpace(ch);
#else
return (xmlCharType.charProperties[ch] & XmlCharType.fWhitespace) != 0;
#endif
}
// Value convertors:
//
// String representation of Base types in XML (xsd) sometimes differ from
// one common language runtime offer and for all types it has to be locale independent.
// o -- means that XmlConvert pass through to common language runtime converter with InvariantInfo FormatInfo
// x -- means we doing something special to make a convertion.
//
// From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Tim Str uid
// ------------------------------------------------------------------------------
// Boolean x
// Char o
// SByte o
// Byte o
// Int16 o
// UInt16 o
// Int32 o
// UInt32 o
// Int64 o
// UInt64 o
// Single x
// Double x
// Decimal o
// DateTime x
// String x o o o o o o o o o o x x o o x
// Guid x
// -----------------------------------------------------------------------------
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Boolean value) {
return value ? "true" : "false";
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Char value) {
return value.ToString(null);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Decimal value) {
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static string ToString(SByte value) {
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Int16 value) {
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Int32 value) {
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString15"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Int64 value) {
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString6"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Byte value) {
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString7"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static string ToString(UInt16 value) {
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString8"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static string ToString(UInt32 value) {
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString16"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static string ToString(UInt64 value) {
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString9"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Single value) {
if (Single.IsNegativeInfinity(value)) return "-INF";
if (Single.IsPositiveInfinity(value)) return "INF";
if (IsNegativeZero((double)value)) {
return("-0");
}
return value.ToString("R", NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString10"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Double value) {
if (Double.IsNegativeInfinity(value)) return "-INF";
if (Double.IsPositiveInfinity(value)) return "INF";
if (IsNegativeZero(value)) {
return("-0");
}
return value.ToString("R", NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString11"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(TimeSpan value) {
return new XsdDuration(value).ToString();
}
#if !SILVERLIGHT
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString12"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Obsolete("Use XmlConvert.ToString() that takes in XmlDateTimeSerializationMode")]
public static string ToString(DateTime value) {
return ToString(value, "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz");
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString13"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(DateTime value, string format) {
return value.ToString(format, DateTimeFormatInfo.InvariantInfo);
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString14"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption) {
switch(dateTimeOption) {
case XmlDateTimeSerializationMode.Local:
value = SwitchToLocalTime(value);
break;
case XmlDateTimeSerializationMode.Utc:
value = SwitchToUtcTime(value);
break;
case XmlDateTimeSerializationMode.Unspecified:
value = new DateTime(value.Ticks, DateTimeKind.Unspecified);
break;
case XmlDateTimeSerializationMode.RoundtripKind:
break;
default:
throw new ArgumentException(Res.GetString(Res.Sch_InvalidDateTimeOption, dateTimeOption, "dateTimeOption"));
}
XsdDateTime xsdDateTime = new XsdDateTime(value, XsdDateTimeFlags.DateTime);
return xsdDateTime.ToString();
}
public static string ToString(DateTimeOffset value) {
XsdDateTime xsdDateTime = new XsdDateTime(value);
return xsdDateTime.ToString();
}
public static string ToString(DateTimeOffset value, string format) {
return value.ToString( format, DateTimeFormatInfo.InvariantInfo );
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString15"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Guid value) {
return value.ToString();
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToBoolean"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Boolean ToBoolean (string s) {
s = TrimString(s);
if (s == "1" || s == "true" ) return true;
if (s == "0" || s == "false") return false;
throw new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Boolean"));
}
#if !SILVERLIGHT
internal static Exception TryToBoolean(string s, out Boolean result) {
s = TrimString(s);
if (s == "0" || s == "false") {
result = false;
return null;
}
else if (s == "1" || s == "true") {
result = true;
return null;
}
result = false;
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Boolean"));
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToChar"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Char ToChar (string s) {
if (s == null) {
throw new ArgumentNullException("s");
}
if (s.Length != 1) {
throw new FormatException(Res.GetString(Res.XmlConvert_NotOneCharString));
}
return s[0];
}
#if !SILVERLIGHT
internal static Exception TryToChar(string s, out Char result) {
if (!Char.TryParse(s, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Char"));
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDecimal"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Decimal ToDecimal (string s) {
return Decimal.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
#if !SILVERLIGHT
internal static Exception TryToDecimal(string s, out Decimal result) {
if (!Decimal.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Decimal"));
}
return null;
}
internal static Decimal ToInteger (string s) {
return Decimal.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
internal static Exception TryToInteger(string s, out Decimal result) {
if (!Decimal.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Integer"));
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToSByte"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static SByte ToSByte (string s) {
return SByte.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
#if !SILVERLIGHT
internal static Exception TryToSByte(string s, out SByte result) {
if (!SByte.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "SByte"));
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt16"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Int16 ToInt16 (string s) {
return Int16.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
#if !SILVERLIGHT
internal static Exception TryToInt16(string s, out Int16 result) {
if (!Int16.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Int16"));
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt32"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Int32 ToInt32 (string s) {
return Int32.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
#if !SILVERLIGHT
internal static Exception TryToInt32(string s, out Int32 result) {
if (!Int32.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Int32"));
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt64"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Int64 ToInt64 (string s) {
return Int64.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
#if !SILVERLIGHT
internal static Exception TryToInt64(string s, out Int64 result) {
if (!Int64.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Int64"));
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToByte"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Byte ToByte (string s) {
return Byte.Parse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
#if !SILVERLIGHT
internal static Exception TryToByte(string s, out Byte result) {
if (!Byte.TryParse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Byte"));
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt16"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static UInt16 ToUInt16 (string s) {
return UInt16.Parse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
#if !SILVERLIGHT
internal static Exception TryToUInt16(string s, out UInt16 result) {
if (!UInt16.TryParse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "UInt16"));
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt32"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static UInt32 ToUInt32 (string s) {
return UInt32.Parse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
#if !SILVERLIGHT
internal static Exception TryToUInt32(string s, out UInt32 result) {
if (!UInt32.TryParse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "UInt32"));
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt64"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static UInt64 ToUInt64 (string s) {
return UInt64.Parse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
#if !SILVERLIGHT
internal static Exception TryToUInt64(string s, out UInt64 result) {
if (!UInt64.TryParse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "UInt64"));
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToSingle"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Single ToSingle (string s) {
s = TrimString(s);
if(s == "-INF") return Single.NegativeInfinity;
if(s == "INF") return Single.PositiveInfinity;
float f = Single.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo);
if (f == 0 && s[0] == '-') {
return -0f;
}
return f;
}
#if !SILVERLIGHT
internal static Exception TryToSingle(string s, out Single result) {
s = TrimString(s);
if (s == "-INF") {
result = Single.NegativeInfinity;
return null;
}
else if (s == "INF") {
result = Single.PositiveInfinity;
return null;
}
else if (!Single.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Single"));
}
if (result == 0 && s[0] == '-') {
result = -0f;
}
return null;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDouble"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Double ToDouble(string s) {
s = TrimString(s);
if(s == "-INF") return Double.NegativeInfinity;
if(s == "INF") return Double.PositiveInfinity;
double dVal = Double.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowExponent|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
if (dVal == 0 && s[0] == '-') {
return -0d;
}
return dVal;
}
#if !SILVERLIGHT
internal static Exception TryToDouble (string s, out double result) {
s = TrimString(s);
if (s == "-INF") {
result = Double.NegativeInfinity;
return null;
}
else if (s == "INF") {
result = Double.PositiveInfinity;
return null;
}
else if (!Double.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Double"));
}
if (result == 0 && s[0] == '-') {
result = -0d;
}
return null;
}
#endif
#if !SILVERLIGHT
internal static Double ToXPathDouble (Object o) {
string str = o as string;
if (str != null) {
str = TrimString(str);
if (str.Length != 0 && str[0] != '+') {
double d;
if (Double.TryParse(str, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out d)) {
return d;
}
}
return Double.NaN;
}
if (o is double) {
return (double) o;
}
if (o is bool) {
return ((bool) o) ? 1.0 : 0.0;
}
try {
return Convert.ToDouble(o, NumberFormatInfo.InvariantInfo);
} catch ( FormatException ) {
} catch ( OverflowException ) {
} catch ( ArgumentNullException ) {}
return Double.NaN;
}
internal static String ToXPathString(Object value){
string s = value as string;
if ( s != null ) {
return s;
}
else if ( value is double ) {
return ((double)value).ToString("R", NumberFormatInfo.InvariantInfo);
}
else if ( value is bool ) {
return (bool)value ? "true" : "false";
}
else {
return Convert.ToString(value, NumberFormatInfo.InvariantInfo);
}
}
internal static Double XPathRound(Double value) {
double temp = Math.Round(value);
return (value - temp == 0.5) ? temp + 1 : temp;
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToTimeSpan"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static TimeSpan ToTimeSpan(string s) {
XsdDuration duration;
TimeSpan timeSpan;
try {
duration = new XsdDuration(s);
}
catch (Exception) {
// Remap exception for v1 compatibility
throw new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "TimeSpan"));
}
timeSpan = duration.ToTimeSpan();
return timeSpan;
}
#if !SILVERLIGHT
internal static Exception TryToTimeSpan(string s, out TimeSpan result) {
XsdDuration duration;
Exception exception;
exception = XsdDuration.TryParse(s, out duration);
if (exception != null) {
result = TimeSpan.MinValue;
return exception;
}
else {
return duration.TryToTimeSpan(out result);
}
}
#endif
#if !SILVERLIGHT
// use AllDateTimeFormats property to access the formats
static volatile string[] s_allDateTimeFormats;
// NOTE: Do not use this property for reference comparison. It may not be unique.
static string[] AllDateTimeFormats {
get {
if ( s_allDateTimeFormats == null ) {
CreateAllDateTimeFormats();
}
return s_allDateTimeFormats;
}
}
static void CreateAllDateTimeFormats() {
if ( s_allDateTimeFormats == null ) {
// no locking; the array is immutable so it's not a problem that it may get initialized more than once
s_allDateTimeFormats = new string[] {
"yyyy-MM-ddTHH:mm:ss.FFFFFFFzzzzzz", //dateTime
"yyyy-MM-ddTHH:mm:ss.FFFFFFF",
"yyyy-MM-ddTHH:mm:ss.FFFFFFFZ",
"HH:mm:ss.FFFFFFF", //time
"HH:mm:ss.FFFFFFFZ",
"HH:mm:ss.FFFFFFFzzzzzz",
"yyyy-MM-dd", // date
"yyyy-MM-ddZ",
"yyyy-MM-ddzzzzzz",
"yyyy-MM", // yearMonth
"yyyy-MMZ",
"yyyy-MMzzzzzz",
"yyyy", // year
"yyyyZ",
"yyyyzzzzzz",
"--MM-dd", // monthDay
"--MM-ddZ",
"--MM-ddzzzzzz",
"---dd", // day
"---ddZ",
"---ddzzzzzz",
"--MM--", // month
"--MM--Z",
"--MM--zzzzzz",
};
}
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Obsolete("Use XmlConvert.ToDateTime() that takes in XmlDateTimeSerializationMode")]
public static DateTime ToDateTime(string s) {
return ToDateTime(s, AllDateTimeFormats);
}
#endif
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static DateTime ToDateTime(string s, string format) {
return DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite|DateTimeStyles.AllowTrailingWhite);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static DateTime ToDateTime(string s, string[] formats) {
return DateTime.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite|DateTimeStyles.AllowTrailingWhite);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static DateTime ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption) {
XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd);
DateTime dt = (DateTime)xsdDateTime;
switch (dateTimeOption) {
case XmlDateTimeSerializationMode.Local:
dt = SwitchToLocalTime(dt);
break;
case XmlDateTimeSerializationMode.Utc:
dt = SwitchToUtcTime(dt);
break;
case XmlDateTimeSerializationMode.Unspecified:
dt = new DateTime(dt.Ticks, DateTimeKind.Unspecified);
break;
case XmlDateTimeSerializationMode.RoundtripKind:
break;
default:
throw new ArgumentException(Res.GetString(Res.Sch_InvalidDateTimeOption, dateTimeOption, "dateTimeOption"));
}
return dt;
}
public static DateTimeOffset ToDateTimeOffset(string s) {
if (s == null) {
throw new ArgumentNullException("s");
}
XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd);
DateTimeOffset dateTimeOffset = (DateTimeOffset)xsdDateTime;
return dateTimeOffset;
}
public static DateTimeOffset ToDateTimeOffset(string s, string format) {
if ( s == null ) {
throw new ArgumentNullException( "s" );
}
return DateTimeOffset.ParseExact( s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite );
}
public static DateTimeOffset ToDateTimeOffset(string s, string[] formats) {
if ( s == null ) {
throw new ArgumentNullException( "s" );
}
return DateTimeOffset.ParseExact( s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite );
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToGuid"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Guid ToGuid (string s) {
return new Guid(s);
}
#if !SILVERLIGHT
internal static Exception TryToGuid(string s, out Guid result) {
Exception exception = null;
result = Guid.Empty;
try {
result = new Guid(s);
}
catch (ArgumentException) {
exception = new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Guid"));
}
catch (FormatException) {
exception = new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Guid"));
}
return exception;
}
#endif
private static DateTime SwitchToLocalTime(DateTime value) {
switch (value.Kind) {
case DateTimeKind.Local:
return value;
case DateTimeKind.Unspecified:
return new DateTime(value.Ticks, DateTimeKind.Local);
case DateTimeKind.Utc:
return value.ToLocalTime();
}
return value;
}
private static DateTime SwitchToUtcTime(DateTime value) {
switch (value.Kind) {
case DateTimeKind.Utc:
return value;
case DateTimeKind.Unspecified:
return new DateTime(value.Ticks, DateTimeKind.Utc);
case DateTimeKind.Local:
return value.ToUniversalTime();
}
return value;
}
internal static Uri ToUri(string s) {
if (s != null && s.Length > 0) { //string.Empty is a valid uri but not " "
s = TrimString(s);
if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) {
throw new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Uri"));
}
}
Uri uri;
if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri)) {
throw new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Uri"));
}
return uri;
}
#if !SILVERLIGHT
internal static Exception TryToUri(string s, out Uri result) {
result = null;
if (s != null && s.Length > 0) { //string.Empty is a valid uri but not " "
s = TrimString(s);
if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Uri"));
}
}
if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out result)) {
return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Uri"));
}
return null;
}
#endif
// Compares the given character interval and string and returns true if the characters are identical
internal static bool StrEqual( char[] chars, int strPos1, int strLen1, string str2 ) {
if ( strLen1 != str2.Length ) {
return false;
}
int i = 0;
while ( i < strLen1 && chars[strPos1+i] == str2[i] ) {
i++;
}
return i == strLen1;
}
// XML whitespace characters, <spec>http://www.w3.org/TR/REC-xml#NT-S</spec>
internal static readonly char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' };
// Trim a string using XML whitespace characters
internal static string TrimString(string value) {
return value.Trim(WhitespaceChars);
}
// Trim beginning of a string using XML whitespace characters
internal static string TrimStringStart(string value) {
return value.TrimStart(WhitespaceChars);
}
// Trim end of a string using XML whitespace characters
internal static string TrimStringEnd(string value) {
return value.TrimEnd(WhitespaceChars);
}
// Split a string into a whitespace-separated list of tokens
internal static string[] SplitString(string value) {
return value.Split(WhitespaceChars, StringSplitOptions.RemoveEmptyEntries);
}
internal static string[] SplitString(string value, StringSplitOptions splitStringOptions) {
return value.Split(WhitespaceChars, splitStringOptions);
}
internal static bool IsNegativeZero(double value) {
// Simple equals function will report that -0 is equal to +0, so compare bits instead
if (value == 0 && DoubleToInt64Bits(value) == DoubleToInt64Bits(-0e0)) {
return true;
}
return false;
}
#if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY
[System.Security.SecuritySafeCritical]
#endif
private static unsafe long DoubleToInt64Bits(double value) {
// NOTE: BitConverter.DoubleToInt64Bits is missing in Silverlight
return *((long*)&value);
}
internal static void VerifyCharData(string data, ExceptionType exceptionType) {
VerifyCharData(data, exceptionType, exceptionType);
}
#if SILVERLIGHT
internal static void VerifyCharData( string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType ) {
#else
internal static unsafe void VerifyCharData( string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType ) {
#endif
if ( data == null || data.Length == 0 ) {
return;
}
int i = 0;
int len = data.Length;
for (;;) {
#if SILVERLIGHT
while (i < len && xmlCharType.IsCharData(data[i])) {
#else
while ( i < len && ( xmlCharType.charProperties[data[i]] & XmlCharType.fCharData ) != 0 ) {
#endif
i++;
}
if ( i == len ) {
return;
}
char ch = data[i];
if ( XmlCharType.IsHighSurrogate( ch ) ) {
if ( i + 1 == len ) {
throw CreateException( Res.Xml_InvalidSurrogateMissingLowChar, invSurrogateExceptionType, 0, i + 1 );
}
ch = data[i+1];
if ( XmlCharType.IsLowSurrogate( ch ) ) {
i += 2;
continue;
}
else {
throw CreateInvalidSurrogatePairException( data[i+1], data[i], invSurrogateExceptionType, 0, i + 1 );
}
}
throw CreateInvalidCharException( data, i, invCharExceptionType );
}
}
#if SILVERLIGHT
internal static void VerifyCharData(char[] data, int offset, int len, ExceptionType exceptionType) {
#else
internal static unsafe void VerifyCharData( char[] data, int offset, int len, ExceptionType exceptionType ) {
#endif
if ( data == null || len == 0 ) {
return;
}
int i = offset;
int endPos = offset + len;
for (;;) {
#if SILVERLIGHT
while ( i < endPos && xmlCharType.IsCharData(data[i])) {
#else
while ( i < endPos && ( xmlCharType.charProperties[data[i]] & XmlCharType.fCharData ) != 0 ) {
#endif
i++;
}
if ( i == endPos ) {
return;
}
char ch = data[i];
if ( XmlCharType.IsHighSurrogate( ch ) ) {
if ( i + 1 == endPos ) {
throw CreateException(Res.Xml_InvalidSurrogateMissingLowChar, exceptionType, 0, offset - i + 1);
}
ch = data[i+1];
if ( XmlCharType.IsLowSurrogate( ch ) ) {
i += 2;
continue;
}
else {
throw CreateInvalidSurrogatePairException(data[i + 1], data[i], exceptionType, 0, offset - i + 1);
}
}
throw CreateInvalidCharException( data, len, i, exceptionType );
}
}
#if !SILVERLIGHT
internal static string EscapeValueForDebuggerDisplay( string value ) {
StringBuilder sb = null;
int i = 0;
int start = 0;
while ( i < value.Length ) {
char ch = value[i];
if ( (int)ch < 0x20 || ch == '"' ) {
if ( sb == null ) {
sb = new StringBuilder( value.Length + 4 );
}
if ( i - start > 0 ) {
sb.Append( value, start, i - start );
}
start = i + 1;
switch ( ch ) {
case '"':
sb.Append( "\\\"" );
break;
case '\r':
sb.Append( "\\r" );
break;
case '\n':
sb.Append( "\\n" );
break;
case '\t':
sb.Append( "\\t" );
break;
default:
sb.Append( ch );
break;
}
}
i++;
}
if ( sb == null ) {
return value;
}
if ( i - start > 0 ) {
sb.Append( value, start, i - start );
}
return sb.ToString();
}
#endif
internal static Exception CreateException( string res, ExceptionType exceptionType ) {
return CreateException( res, exceptionType, 0, 0 );
}
internal static Exception CreateException( string res, ExceptionType exceptionType, int lineNo, int linePos ) {
switch ( exceptionType ) {
case ExceptionType.ArgumentException:
return new ArgumentException( Res.GetString( res ) );
case ExceptionType.XmlException:
default:
return new XmlException( res, string.Empty, lineNo, linePos );
}
}
internal static Exception CreateException( string res, string arg, ExceptionType exceptionType ) {
return CreateException( res, arg, exceptionType, 0, 0 );
}
internal static Exception CreateException( string res, string arg, ExceptionType exceptionType, int lineNo, int linePos ) {
switch ( exceptionType ) {
case ExceptionType.ArgumentException:
return new ArgumentException( Res.GetString( res, arg ) );
case ExceptionType.XmlException:
default:
return new XmlException( res, arg, lineNo, linePos );
}
}
internal static Exception CreateException( string res, string[] args, ExceptionType exceptionType ) {
return CreateException(res, args, exceptionType, 0, 0);
}
internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType, int lineNo, int linePos) {
switch ( exceptionType ) {
case ExceptionType.ArgumentException:
return new ArgumentException( Res.GetString( res, args ) );
case ExceptionType.XmlException:
default:
return new XmlException( res, args, lineNo, linePos );
}
}
internal static Exception CreateInvalidSurrogatePairException( char low, char hi ) {
return CreateInvalidSurrogatePairException( low, hi, ExceptionType.ArgumentException );
}
internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType) {
return CreateInvalidSurrogatePairException(low, hi, exceptionType, 0, 0);
}
internal static Exception CreateInvalidSurrogatePairException( char low, char hi, ExceptionType exceptionType, int lineNo, int linePos ) {
string[] args = new string[] {
((uint)hi).ToString( "X", CultureInfo.InvariantCulture ),
((uint)low).ToString( "X", CultureInfo.InvariantCulture )
} ;
return CreateException( Res.Xml_InvalidSurrogatePairWithArgs, args, exceptionType, lineNo, linePos );
}
internal static Exception CreateInvalidHighSurrogateCharException( char hi ) {
return CreateInvalidHighSurrogateCharException( hi, ExceptionType.ArgumentException );
}
internal static Exception CreateInvalidHighSurrogateCharException( char hi, ExceptionType exceptionType ) {
return CreateInvalidHighSurrogateCharException( hi, exceptionType, 0, 0);
}
internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType, int lineNo, int linePos) {
return CreateException( Res.Xml_InvalidSurrogateHighChar, ((uint)hi).ToString( "X", CultureInfo.InvariantCulture ), exceptionType, lineNo, linePos );
}
internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos) {
return CreateInvalidCharException(data, length, invCharPos, ExceptionType.ArgumentException);
}
internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos, ExceptionType exceptionType) {
return CreateException(Res.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, length, invCharPos), exceptionType, 0, invCharPos + 1);
}
internal static Exception CreateInvalidCharException( string data, int invCharPos ) {
return CreateInvalidCharException( data, invCharPos, ExceptionType.ArgumentException );
}
internal static Exception CreateInvalidCharException( string data, int invCharPos, ExceptionType exceptionType ) {
return CreateException(Res.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, invCharPos), exceptionType, 0, invCharPos + 1);
}
internal static Exception CreateInvalidCharException( char invChar, char nextChar ) {
return CreateInvalidCharException(invChar, nextChar, ExceptionType.ArgumentException);
}
internal static Exception CreateInvalidCharException( char invChar, char nextChar, ExceptionType exceptionType) {
return CreateException(Res.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(invChar, nextChar), exceptionType);
}
internal static Exception CreateInvalidNameCharException(string name, int index, ExceptionType exceptionType) {
return CreateException(index == 0 ? Res.Xml_BadStartNameChar : Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, index), exceptionType, 0, index + 1);
}
internal static ArgumentException CreateInvalidNameArgumentException(string name, string argumentName) {
return ( name == null ) ? new ArgumentNullException( argumentName ) : new ArgumentException( Res.GetString( Res.Xml_EmptyName ), argumentName );
}
}
}
|