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 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
|
//------------------------------------------------------------------------------
// <copyright file="XmlReader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
//------------------------------------------------------------------------------
using System.IO;
using System.Text;
using System.Security;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.Security.Permissions;
using System.Xml.Schema;
using System.Runtime.Versioning;
#if SILVERLIGHT
using BufferBuilder=System.Xml.BufferBuilder;
#else
using BufferBuilder = System.Text.StringBuilder;
#endif
namespace System.Xml {
// Represents a reader that provides fast, non-cached forward only stream access to XML data.
#if !SILVERLIGHT // This is used for displaying the state of the XmlReader in Watch/Locals windows in the Visual Studio during debugging
[DebuggerDisplay("{debuggerDisplayProxy}")]
#endif
public abstract partial class XmlReader : IDisposable {
static private uint IsTextualNodeBitmap = 0x6018; // 00 0110 0000 0001 1000
// 0 None,
// 0 Element,
// 0 Attribute,
// 1 Text,
// 1 CDATA,
// 0 EntityReference,
// 0 Entity,
// 0 ProcessingInstruction,
// 0 Comment,
// 0 Document,
// 0 DocumentType,
// 0 DocumentFragment,
// 0 Notation,
// 1 Whitespace,
// 1 SignificantWhitespace,
// 0 EndElement,
// 0 EndEntity,
// 0 XmlDeclaration
static private uint CanReadContentAsBitmap = 0x1E1BC; // 01 1110 0001 1011 1100
// 0 None,
// 0 Element,
// 1 Attribute,
// 1 Text,
// 1 CDATA,
// 1 EntityReference,
// 0 Entity,
// 1 ProcessingInstruction,
// 1 Comment,
// 0 Document,
// 0 DocumentType,
// 0 DocumentFragment,
// 0 Notation,
// 1 Whitespace,
// 1 SignificantWhitespace,
// 1 EndElement,
// 1 EndEntity,
// 0 XmlDeclaration
static private uint HasValueBitmap = 0x2659C; // 10 0110 0101 1001 1100
// 0 None,
// 0 Element,
// 1 Attribute,
// 1 Text,
// 1 CDATA,
// 0 EntityReference,
// 0 Entity,
// 1 ProcessingInstruction,
// 1 Comment,
// 0 Document,
// 1 DocumentType,
// 0 DocumentFragment,
// 0 Notation,
// 1 Whitespace,
// 1 SignificantWhitespace,
// 0 EndElement,
// 0 EndEntity,
// 1 XmlDeclaration
//
// Constants
//
internal const int DefaultBufferSize = 4096;
internal const int BiggerBufferSize = 8192;
internal const int MaxStreamLengthForDefaultBufferSize = 64 * 1024; // 64kB
internal const int AsyncBufferSize = 64 * 1024; //64KB
// Settings
public virtual XmlReaderSettings Settings {
get {
return null;
}
}
// Node Properties
// Get the type of the current node.
public abstract XmlNodeType NodeType { get; }
// Gets the name of the current node, including the namespace prefix.
public virtual string Name {
get {
if (Prefix.Length == 0) {
return LocalName;
}
else {
return NameTable.Add(string.Concat(Prefix, ":", LocalName));
}
}
}
// Gets the name of the current node without the namespace prefix.
public abstract string LocalName { get; }
// Gets the namespace URN (as defined in the W3C Namespace Specification) of the current namespace scope.
public abstract string NamespaceURI { get; }
// Gets the namespace prefix associated with the current node.
public abstract string Prefix { get; }
// Gets a value indicating whether
public virtual bool HasValue {
get {
return HasValueInternal(this.NodeType);
}
}
// Gets the text value of the current node.
public abstract string Value { get; }
// Gets the depth of the current node in the XML element stack.
public abstract int Depth { get; }
// Gets the base URI of the current node.
public abstract string BaseURI { get; }
// Gets a value indicating whether the current node is an empty element (for example, <MyElement/>).
public abstract bool IsEmptyElement { get; }
// Gets a value indicating whether the current node is an attribute that was generated from the default value defined
// in the DTD or schema.
public virtual bool IsDefault {
get {
return false;
}
}
#if !SILVERLIGHT
// Gets the quotation mark character used to enclose the value of an attribute node.
public virtual char QuoteChar {
get {
return '"';
}
}
#endif
// Gets the current xml:space scope.
public virtual XmlSpace XmlSpace {
get {
return XmlSpace.None;
}
}
// Gets the current xml:lang scope.
public virtual string XmlLang {
get {
return string.Empty;
}
}
#if !SILVERLIGHT // Removing dependency on XmlSchema
// returns the schema info interface of the reader
public virtual IXmlSchemaInfo SchemaInfo {
get {
return this as IXmlSchemaInfo;
}
}
#endif
// returns the type of the current node
public virtual System.Type ValueType {
get {
return typeof(string);
}
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and returns the content as the most appropriate type (by default as string). Stops at start tags and end tags.
public virtual object ReadContentAsObject() {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAsObject");
}
return InternalReadContentAsString();
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and converts the content to a boolean. Stops at start tags and end tags.
public virtual bool ReadContentAsBoolean() {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAsBoolean");
}
try {
return XmlConvert.ToBoolean(InternalReadContentAsString());
}
catch (FormatException e) {
throw new XmlException(Res.Xml_ReadContentAsFormatException, "Boolean", e, this as IXmlLineInfo);
}
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and converts the content to a DateTime. Stops at start tags and end tags.
public virtual DateTime ReadContentAsDateTime() {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAsDateTime");
}
try {
return XmlConvert.ToDateTime(InternalReadContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
}
catch (FormatException e) {
throw new XmlException(Res.Xml_ReadContentAsFormatException, "DateTime", e, this as IXmlLineInfo);
}
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and converts the content to a DateTimeOffset. Stops at start tags and end tags.
public virtual DateTimeOffset ReadContentAsDateTimeOffset() {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAsDateTimeOffset");
}
try {
return XmlConvert.ToDateTimeOffset(InternalReadContentAsString());
}
catch (FormatException e) {
throw new XmlException(Res.Xml_ReadContentAsFormatException, "DateTimeOffset", e, this as IXmlLineInfo);
}
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and converts the content to a double. Stops at start tags and end tags.
public virtual double ReadContentAsDouble() {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAsDouble");
}
try {
return XmlConvert.ToDouble(InternalReadContentAsString());
}
catch (FormatException e) {
throw new XmlException(Res.Xml_ReadContentAsFormatException, "Double", e, this as IXmlLineInfo);
}
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and converts the content to a float. Stops at start tags and end tags.
public virtual float ReadContentAsFloat() {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAsFloat");
}
try {
return XmlConvert.ToSingle(InternalReadContentAsString());
}
catch (FormatException e) {
throw new XmlException(Res.Xml_ReadContentAsFormatException, "Float", e, this as IXmlLineInfo);
}
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and converts the content to a decimal. Stops at start tags and end tags.
public virtual decimal ReadContentAsDecimal() {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAsDecimal");
}
try {
return XmlConvert.ToDecimal(InternalReadContentAsString());
}
catch (FormatException e) {
throw new XmlException(Res.Xml_ReadContentAsFormatException, "Decimal", e, this as IXmlLineInfo);
}
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and converts the content to an int. Stops at start tags and end tags.
public virtual int ReadContentAsInt() {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAsInt");
}
try {
return XmlConvert.ToInt32(InternalReadContentAsString());
}
catch (FormatException e) {
throw new XmlException(Res.Xml_ReadContentAsFormatException, "Int", e, this as IXmlLineInfo);
}
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and converts the content to a long. Stops at start tags and end tags.
public virtual long ReadContentAsLong() {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAsLong");
}
try {
return XmlConvert.ToInt64(InternalReadContentAsString());
}
catch (FormatException e) {
throw new XmlException(Res.Xml_ReadContentAsFormatException, "Long", e, this as IXmlLineInfo);
}
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and returns the content as a string. Stops at start tags and end tags.
public virtual string ReadContentAsString() {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAsString");
}
return InternalReadContentAsString();
}
// Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references,
// and converts the content to the requested type. Stops at start tags and end tags.
public virtual object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) {
if (!CanReadContentAs()) {
throw CreateReadContentAsException("ReadContentAs");
}
string strContentValue = InternalReadContentAsString();
if (returnType == typeof(string)) {
return strContentValue;
}
else {
try {
#if SILVERLIGHT
return XmlUntypedStringConverter.Instance.FromString(strContentValue, returnType, (namespaceResolver == null ? this as IXmlNamespaceResolver : namespaceResolver));
#else
return XmlUntypedConverter.Untyped.ChangeType(strContentValue, returnType, (namespaceResolver == null ? this as IXmlNamespaceResolver : namespaceResolver));
#endif
}
catch (FormatException e) {
throw new XmlException(Res.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
catch (InvalidCastException e) {
throw new XmlException(Res.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
}
}
// Returns the content of the current element as the most appropriate type. Moves to the node following the element's end tag.
public virtual object ReadElementContentAsObject() {
if (SetupReadElementContentAsXxx("ReadElementContentAsObject")) {
object value = ReadContentAsObject();
FinishReadElementContentAsXxx();
return value;
}
return string.Empty;
}
// Checks local name and namespace of the current element and returns its content as the most appropriate type. Moves to the node following the element's end tag.
public virtual object ReadElementContentAsObject(string localName, string namespaceURI) {
CheckElement(localName, namespaceURI);
return ReadElementContentAsObject();
}
// Returns the content of the current element as a boolean. Moves to the node following the element's end tag.
public virtual bool ReadElementContentAsBoolean() {
if (SetupReadElementContentAsXxx("ReadElementContentAsBoolean")) {
bool value = ReadContentAsBoolean();
FinishReadElementContentAsXxx();
return value;
}
return XmlConvert.ToBoolean(string.Empty);
}
// Checks local name and namespace of the current element and returns its content as a boolean. Moves to the node following the element's end tag.
public virtual bool ReadElementContentAsBoolean(string localName, string namespaceURI) {
CheckElement(localName, namespaceURI);
return ReadElementContentAsBoolean();
}
// Returns the content of the current element as a DateTime. Moves to the node following the element's end tag.
public virtual DateTime ReadElementContentAsDateTime() {
if (SetupReadElementContentAsXxx("ReadElementContentAsDateTime")) {
DateTime value = ReadContentAsDateTime();
FinishReadElementContentAsXxx();
return value;
}
return XmlConvert.ToDateTime(string.Empty, XmlDateTimeSerializationMode.RoundtripKind);
}
// Checks local name and namespace of the current element and returns its content as a DateTime.
// Moves to the node following the element's end tag.
public virtual DateTime ReadElementContentAsDateTime(string localName, string namespaceURI) {
CheckElement(localName, namespaceURI);
return ReadElementContentAsDateTime();
}
// Returns the content of the current element as a double. Moves to the node following the element's end tag.
public virtual double ReadElementContentAsDouble() {
if (SetupReadElementContentAsXxx("ReadElementContentAsDouble")) {
double value = ReadContentAsDouble();
FinishReadElementContentAsXxx();
return value;
}
return XmlConvert.ToDouble(string.Empty);
}
// Checks local name and namespace of the current element and returns its content as a double.
// Moves to the node following the element's end tag.
public virtual double ReadElementContentAsDouble(string localName, string namespaceURI) {
CheckElement(localName, namespaceURI);
return ReadElementContentAsDouble();
}
// Returns the content of the current element as a float. Moves to the node following the element's end tag.
public virtual float ReadElementContentAsFloat() {
if (SetupReadElementContentAsXxx("ReadElementContentAsFloat")) {
float value = ReadContentAsFloat();
FinishReadElementContentAsXxx();
return value;
}
return XmlConvert.ToSingle(string.Empty);
}
// Checks local name and namespace of the current element and returns its content as a float.
// Moves to the node following the element's end tag.
public virtual float ReadElementContentAsFloat(string localName, string namespaceURI) {
CheckElement(localName, namespaceURI);
return ReadElementContentAsFloat();
}
// Returns the content of the current element as a decimal. Moves to the node following the element's end tag.
public virtual decimal ReadElementContentAsDecimal() {
if (SetupReadElementContentAsXxx("ReadElementContentAsDecimal")) {
decimal value = ReadContentAsDecimal();
FinishReadElementContentAsXxx();
return value;
}
return XmlConvert.ToDecimal(string.Empty);
}
// Checks local name and namespace of the current element and returns its content as a decimal.
// Moves to the node following the element's end tag.
public virtual decimal ReadElementContentAsDecimal(string localName, string namespaceURI) {
CheckElement(localName, namespaceURI);
return ReadElementContentAsDecimal();
}
// Returns the content of the current element as an int. Moves to the node following the element's end tag.
public virtual int ReadElementContentAsInt() {
if (SetupReadElementContentAsXxx("ReadElementContentAsInt")) {
int value = ReadContentAsInt();
FinishReadElementContentAsXxx();
return value;
}
return XmlConvert.ToInt32(string.Empty);
}
// Checks local name and namespace of the current element and returns its content as an int.
// Moves to the node following the element's end tag.
public virtual int ReadElementContentAsInt(string localName, string namespaceURI) {
CheckElement(localName, namespaceURI);
return ReadElementContentAsInt();
}
// Returns the content of the current element as a long. Moves to the node following the element's end tag.
public virtual long ReadElementContentAsLong() {
if (SetupReadElementContentAsXxx("ReadElementContentAsLong")) {
long value = ReadContentAsLong();
FinishReadElementContentAsXxx();
return value;
}
return XmlConvert.ToInt64(string.Empty);
}
// Checks local name and namespace of the current element and returns its content as a long.
// Moves to the node following the element's end tag.
public virtual long ReadElementContentAsLong(string localName, string namespaceURI) {
CheckElement(localName, namespaceURI);
return ReadElementContentAsLong();
}
// Returns the content of the current element as a string. Moves to the node following the element's end tag.
public virtual string ReadElementContentAsString() {
if (SetupReadElementContentAsXxx("ReadElementContentAsString")) {
string value = ReadContentAsString();
FinishReadElementContentAsXxx();
return value;
}
return string.Empty;
}
// Checks local name and namespace of the current element and returns its content as a string.
// Moves to the node following the element's end tag.
public virtual string ReadElementContentAsString(string localName, string namespaceURI) {
CheckElement(localName, namespaceURI);
return ReadElementContentAsString();
}
// Returns the content of the current element as the requested type. Moves to the node following the element's end tag.
public virtual object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) {
if (SetupReadElementContentAsXxx("ReadElementContentAs")) {
object value = ReadContentAs(returnType, namespaceResolver);
FinishReadElementContentAsXxx();
return value;
}
#if SILVERLIGHT
return (returnType == typeof(string)) ? string.Empty : XmlUntypedStringConverter.Instance.FromString(string.Empty, returnType, namespaceResolver);
#else
return (returnType == typeof(string)) ? string.Empty : XmlUntypedConverter.Untyped.ChangeType(string.Empty, returnType, namespaceResolver);
#endif
}
// Checks local name and namespace of the current element and returns its content as the requested type.
// Moves to the node following the element's end tag.
public virtual object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) {
CheckElement(localName, namespaceURI);
return ReadElementContentAs(returnType, namespaceResolver);
}
// Attribute Accessors
// The number of attributes on the current node.
public abstract int AttributeCount { get; }
// Gets the value of the attribute with the specified Name
public abstract string GetAttribute(string name);
// Gets the value of the attribute with the LocalName and NamespaceURI
public abstract string GetAttribute(string name, string namespaceURI);
// Gets the value of the attribute with the specified index.
public abstract string GetAttribute(int i);
// Gets the value of the attribute with the specified index.
public virtual string this[int i] {
get {
return GetAttribute(i);
}
}
// Gets the value of the attribute with the specified Name.
public virtual string this[string name] {
get {
return GetAttribute(name);
}
}
// Gets the value of the attribute with the LocalName and NamespaceURI
public virtual string this[string name, string namespaceURI] {
get {
return GetAttribute(name, namespaceURI);
}
}
// Moves to the attribute with the specified Name.
public abstract bool MoveToAttribute(string name);
// Moves to the attribute with the specified LocalName and NamespaceURI.
public abstract bool MoveToAttribute(string name, string ns);
// Moves to the attribute with the specified index.
public virtual void MoveToAttribute(int i) {
if (i < 0 || i >= AttributeCount) {
throw new ArgumentOutOfRangeException("i");
}
MoveToElement();
MoveToFirstAttribute();
int j = 0;
while (j < i) {
MoveToNextAttribute();
j++;
}
}
// Moves to the first attribute of the current node.
public abstract bool MoveToFirstAttribute();
// Moves to the next attribute.
public abstract bool MoveToNextAttribute();
// Moves to the element that contains the current attribute node.
public abstract bool MoveToElement();
// Parses the attribute value into one or more Text and/or EntityReference node types.
public abstract bool ReadAttributeValue();
// Moving through the Stream
// Reads the next node from the stream.
public abstract bool Read();
// Returns true when the XmlReader is positioned at the end of the stream.
public abstract bool EOF { get; }
// Closes the stream/TextReader (if CloseInput==true), changes the ReadState to Closed, and sets all the properties back to zero/empty string.
public virtual void Close() { }
// Returns the read state of the XmlReader.
public abstract ReadState ReadState { get; }
// Skips to the end tag of the current element.
public virtual void Skip() {
if (ReadState != ReadState.Interactive) {
return;
}
SkipSubtree();
}
// Gets the XmlNameTable associated with the XmlReader.
public abstract XmlNameTable NameTable { get; }
// Resolves a namespace prefix in the current element's scope.
public abstract string LookupNamespace(string prefix);
// Returns true if the XmlReader can expand general entities.
public virtual bool CanResolveEntity {
get {
return false;
}
}
// Resolves the entity reference for nodes of NodeType EntityReference.
public abstract void ResolveEntity();
// Binary content access methods
// Returns true if the reader supports call to ReadContentAsBase64, ReadElementContentAsBase64, ReadContentAsBinHex and ReadElementContentAsBinHex.
public virtual bool CanReadBinaryContent {
get {
return false;
}
}
// Returns decoded bytes of the current base64 text content. Call this methods until it returns 0 to get all the data.
public virtual int ReadContentAsBase64(byte[] buffer, int index, int count) {
throw new NotSupportedException(Res.GetString(Res.Xml_ReadBinaryContentNotSupported, "ReadContentAsBase64"));
}
// Returns decoded bytes of the current base64 element content. Call this methods until it returns 0 to get all the data.
public virtual int ReadElementContentAsBase64(byte[] buffer, int index, int count) {
throw new NotSupportedException(Res.GetString(Res.Xml_ReadBinaryContentNotSupported, "ReadElementContentAsBase64"));
}
// Returns decoded bytes of the current binhex text content. Call this methods until it returns 0 to get all the data.
public virtual int ReadContentAsBinHex(byte[] buffer, int index, int count) {
throw new NotSupportedException(Res.GetString(Res.Xml_ReadBinaryContentNotSupported, "ReadContentAsBinHex"));
}
// Returns decoded bytes of the current binhex element content. Call this methods until it returns 0 to get all the data.
public virtual int ReadElementContentAsBinHex(byte[] buffer, int index, int count) {
throw new NotSupportedException(Res.GetString(Res.Xml_ReadBinaryContentNotSupported, "ReadElementContentAsBinHex"));
}
// Text streaming methods
// Returns true if the XmlReader supports calls to ReadValueChunk.
public virtual bool CanReadValueChunk {
get {
return false;
}
}
// Returns a chunk of the value of the current node. Call this method in a loop to get all the data.
// Use this method to get a streaming access to the value of the current node.
public virtual int ReadValueChunk(char[] buffer, int index, int count) {
throw new NotSupportedException(Res.GetString(Res.Xml_ReadValueChunkNotSupported));
}
#if !SILVERLIGHT
// Virtual helper methods
// Reads the contents of an element as a string. Stops of comments, PIs or entity references.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public virtual string ReadString() {
if (this.ReadState != ReadState.Interactive) {
return string.Empty;
}
this.MoveToElement();
if (this.NodeType == XmlNodeType.Element) {
if (this.IsEmptyElement) {
return string.Empty;
}
else if (!this.Read()) {
throw new InvalidOperationException(Res.GetString(Res.Xml_InvalidOperation));
}
if (this.NodeType == XmlNodeType.EndElement) {
return string.Empty;
}
}
string result = string.Empty;
while (IsTextualNode(this.NodeType)) {
result += this.Value;
if (!this.Read()) {
break;
}
}
return result;
}
#endif
// Checks whether the current node is a content (non-whitespace text, CDATA, Element, EndElement, EntityReference
// or EndEntity) node. If the node is not a content node, then the method skips ahead to the next content node or
// end of file. Skips over nodes of type ProcessingInstruction, DocumentType, Comment, Whitespace and SignificantWhitespace.
public virtual XmlNodeType MoveToContent() {
do {
switch (this.NodeType) {
case XmlNodeType.Attribute:
MoveToElement();
goto case XmlNodeType.Element;
case XmlNodeType.Element:
case XmlNodeType.EndElement:
case XmlNodeType.CDATA:
case XmlNodeType.Text:
case XmlNodeType.EntityReference:
case XmlNodeType.EndEntity:
return this.NodeType;
}
} while (Read());
return this.NodeType;
}
// Checks that the current node is an element and advances the reader to the next node.
public virtual void ReadStartElement() {
if (MoveToContent() != XmlNodeType.Element) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
}
Read();
}
// Checks that the current content node is an element with the given Name and advances the reader to the next node.
public virtual void ReadStartElement(string name) {
if (MoveToContent() != XmlNodeType.Element) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
}
if (this.Name == name) {
Read();
}
else {
throw new XmlException(Res.Xml_ElementNotFound, name, this as IXmlLineInfo);
}
}
// Checks that the current content node is an element with the given LocalName and NamespaceURI
// and advances the reader to the next node.
public virtual void ReadStartElement(string localname, string ns) {
if (MoveToContent() != XmlNodeType.Element) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
}
if (this.LocalName == localname && this.NamespaceURI == ns) {
Read();
}
else {
throw new XmlException(Res.Xml_ElementNotFoundNs, new string[2] { localname, ns }, this as IXmlLineInfo);
}
}
#if !SILVERLIGHT
// Reads a text-only element.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public virtual string ReadElementString() {
string result = string.Empty;
if (MoveToContent() != XmlNodeType.Element) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
}
if (!this.IsEmptyElement) {
Read();
result = ReadString();
if (this.NodeType != XmlNodeType.EndElement) {
throw new XmlException(Res.Xml_UnexpectedNodeInSimpleContent, new string[] { this.NodeType.ToString(), "ReadElementString" }, this as IXmlLineInfo);
}
Read();
}
else {
Read();
}
return result;
}
// Checks that the Name property of the element found matches the given string before reading a text-only element.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public virtual string ReadElementString(string name) {
string result = string.Empty;
if (MoveToContent() != XmlNodeType.Element) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
}
if (this.Name != name) {
throw new XmlException(Res.Xml_ElementNotFound, name, this as IXmlLineInfo);
}
if (!this.IsEmptyElement) {
//Read();
result = ReadString();
if (this.NodeType != XmlNodeType.EndElement) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
}
Read();
}
else {
Read();
}
return result;
}
// Checks that the LocalName and NamespaceURI properties of the element found matches the given strings
// before reading a text-only element.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public virtual string ReadElementString(string localname, string ns) {
string result = string.Empty;
if (MoveToContent() != XmlNodeType.Element) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
}
if (this.LocalName != localname || this.NamespaceURI != ns) {
throw new XmlException(Res.Xml_ElementNotFoundNs, new string[2] { localname, ns }, this as IXmlLineInfo);
}
if (!this.IsEmptyElement) {
//Read();
result = ReadString();
if (this.NodeType != XmlNodeType.EndElement) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
}
Read();
}
else {
Read();
}
return result;
}
#endif
// Checks that the current content node is an end tag and advances the reader to the next node.
public virtual void ReadEndElement() {
if (MoveToContent() != XmlNodeType.EndElement) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
}
Read();
}
// Calls MoveToContent and tests if the current content node is a start tag or empty element tag (XmlNodeType.Element).
public virtual bool IsStartElement() {
return MoveToContent() == XmlNodeType.Element;
}
// Calls MoveToContentand tests if the current content node is a start tag or empty element tag (XmlNodeType.Element) and if the
// Name property of the element found matches the given argument.
public virtual bool IsStartElement(string name) {
return (MoveToContent() == XmlNodeType.Element) &&
(this.Name == name);
}
// Calls MoveToContent and tests if the current content node is a start tag or empty element tag (XmlNodeType.Element) and if
// the LocalName and NamespaceURI properties of the element found match the given strings.
public virtual bool IsStartElement(string localname, string ns) {
return (MoveToContent() == XmlNodeType.Element) &&
(this.LocalName == localname && this.NamespaceURI == ns);
}
// Reads to the following element with the given Name.
public virtual bool ReadToFollowing(string name) {
if (name == null || name.Length == 0) {
throw XmlConvert.CreateInvalidNameArgumentException(name, "name");
}
// atomize name
name = NameTable.Add(name);
// find following element with that name
while (Read()) {
if (NodeType == XmlNodeType.Element && Ref.Equal(name, Name)) {
return true;
}
}
return false;
}
// Reads to the following element with the given LocalName and NamespaceURI.
public virtual bool ReadToFollowing(string localName, string namespaceURI) {
if (localName == null || localName.Length == 0) {
throw XmlConvert.CreateInvalidNameArgumentException(localName, "localName");
}
if (namespaceURI == null) {
throw new ArgumentNullException("namespaceURI");
}
// atomize local name and namespace
localName = NameTable.Add(localName);
namespaceURI = NameTable.Add(namespaceURI);
// find following element with that name
while (Read()) {
if (NodeType == XmlNodeType.Element && Ref.Equal(localName, LocalName) && Ref.Equal(namespaceURI, NamespaceURI)) {
return true;
}
}
return false;
}
// Reads to the first descendant of the current element with the given Name.
public virtual bool ReadToDescendant(string name) {
if (name == null || name.Length == 0) {
throw XmlConvert.CreateInvalidNameArgumentException(name, "name");
}
// save the element or root depth
int parentDepth = Depth;
if (NodeType != XmlNodeType.Element) {
// adjust the depth if we are on root node
if (ReadState == ReadState.Initial) {
Debug.Assert(parentDepth == 0);
parentDepth--;
}
else {
return false;
}
}
else if (IsEmptyElement) {
return false;
}
// atomize name
name = NameTable.Add(name);
// find the descendant
while (Read() && Depth > parentDepth) {
if (NodeType == XmlNodeType.Element && Ref.Equal(name, Name)) {
return true;
}
}
Debug.Assert(NodeType == XmlNodeType.EndElement || NodeType == XmlNodeType.None || ReadState == ReadState.Error);
return false;
}
// Reads to the first descendant of the current element with the given LocalName and NamespaceURI.
public virtual bool ReadToDescendant(string localName, string namespaceURI) {
if (localName == null || localName.Length == 0) {
throw XmlConvert.CreateInvalidNameArgumentException(localName, "localName");
}
if (namespaceURI == null) {
throw new ArgumentNullException("namespaceURI");
}
// save the element or root depth
int parentDepth = Depth;
if (NodeType != XmlNodeType.Element) {
// adjust the depth if we are on root node
if (ReadState == ReadState.Initial) {
Debug.Assert(parentDepth == 0);
parentDepth--;
}
else {
return false;
}
}
else if (IsEmptyElement) {
return false;
}
// atomize local name and namespace
localName = NameTable.Add(localName);
namespaceURI = NameTable.Add(namespaceURI);
// find the descendant
while (Read() && Depth > parentDepth) {
if (NodeType == XmlNodeType.Element && Ref.Equal(localName, LocalName) && Ref.Equal(namespaceURI, NamespaceURI)) {
return true;
}
}
Debug.Assert(NodeType == XmlNodeType.EndElement);
return false;
}
// Reads to the next sibling of the current element with the given Name.
public virtual bool ReadToNextSibling(string name) {
if (name == null || name.Length == 0) {
throw XmlConvert.CreateInvalidNameArgumentException(name, "name");
}
// atomize name
name = NameTable.Add(name);
// find the next sibling
XmlNodeType nt;
do {
if (!SkipSubtree()) {
break;
}
nt = NodeType;
if (nt == XmlNodeType.Element && Ref.Equal(name, Name)) {
return true;
}
} while (nt != XmlNodeType.EndElement && !EOF);
return false;
}
// Reads to the next sibling of the current element with the given LocalName and NamespaceURI.
public virtual bool ReadToNextSibling(string localName, string namespaceURI) {
if (localName == null || localName.Length == 0) {
throw XmlConvert.CreateInvalidNameArgumentException(localName, "localName");
}
if (namespaceURI == null) {
throw new ArgumentNullException("namespaceURI");
}
// atomize local name and namespace
localName = NameTable.Add(localName);
namespaceURI = NameTable.Add(namespaceURI);
// find the next sibling
XmlNodeType nt;
do {
if (!SkipSubtree()) {
break;
}
nt = NodeType;
if (nt == XmlNodeType.Element && Ref.Equal(localName, LocalName) && Ref.Equal(namespaceURI, NamespaceURI)) {
return true;
}
} while (nt != XmlNodeType.EndElement && !EOF);
return false;
}
// Returns true if the given argument is a valid Name.
public static bool IsName(string str) {
if (str == null) {
throw new NullReferenceException();
}
return ValidateNames.IsNameNoNamespaces(str);
}
// Returns true if the given argument is a valid NmToken.
public static bool IsNameToken(string str) {
if (str == null) {
throw new NullReferenceException();
}
return ValidateNames.IsNmtokenNoNamespaces(str);
}
// Returns the inner content (including markup) of an element or attribute as a string.
public virtual string ReadInnerXml() {
if (ReadState != ReadState.Interactive) {
return string.Empty;
}
if ((this.NodeType != XmlNodeType.Attribute) && (this.NodeType != XmlNodeType.Element)) {
Read();
return string.Empty;
}
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlWriter xtw = CreateWriterForInnerOuterXml(sw);
try {
if (this.NodeType == XmlNodeType.Attribute) {
#if !SILVERLIGHT // Removing dependency on XmlTextWriter
((XmlTextWriter)xtw).QuoteChar = this.QuoteChar;
#endif
WriteAttributeValue(xtw);
}
if (this.NodeType == XmlNodeType.Element) {
this.WriteNode(xtw, false);
}
}
finally {
xtw.Close();
}
return sw.ToString();
}
// Writes the content (inner XML) of the current node into the provided XmlWriter.
private void WriteNode(XmlWriter xtw, bool defattr) {
#if !SILVERLIGHT
Debug.Assert(xtw is XmlTextWriter);
#endif
int d = this.NodeType == XmlNodeType.None ? -1 : this.Depth;
while (this.Read() && (d < this.Depth)) {
switch (this.NodeType) {
case XmlNodeType.Element:
xtw.WriteStartElement(this.Prefix, this.LocalName, this.NamespaceURI);
#if !SILVERLIGHT // Removing dependency on XmlTextWriter
((XmlTextWriter)xtw).QuoteChar = this.QuoteChar;
#endif
xtw.WriteAttributes(this, defattr);
if (this.IsEmptyElement) {
xtw.WriteEndElement();
}
break;
case XmlNodeType.Text:
xtw.WriteString(this.Value);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
xtw.WriteWhitespace(this.Value);
break;
case XmlNodeType.CDATA:
xtw.WriteCData(this.Value);
break;
case XmlNodeType.EntityReference:
xtw.WriteEntityRef(this.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
xtw.WriteProcessingInstruction(this.Name, this.Value);
break;
case XmlNodeType.DocumentType:
xtw.WriteDocType(this.Name, this.GetAttribute("PUBLIC"), this.GetAttribute("SYSTEM"), this.Value);
break;
case XmlNodeType.Comment:
xtw.WriteComment(this.Value);
break;
case XmlNodeType.EndElement:
xtw.WriteFullEndElement();
break;
}
}
if (d == this.Depth && this.NodeType == XmlNodeType.EndElement) {
Read();
}
}
// Writes the attribute into the provided XmlWriter.
private void WriteAttributeValue(XmlWriter xtw) {
string attrName = this.Name;
while (ReadAttributeValue()) {
if (this.NodeType == XmlNodeType.EntityReference) {
xtw.WriteEntityRef(this.Name);
}
else {
xtw.WriteString(this.Value);
}
}
this.MoveToAttribute(attrName);
}
// Returns the current element and its descendants or an attribute as a string.
public virtual string ReadOuterXml() {
if (ReadState != ReadState.Interactive) {
return string.Empty;
}
if ((this.NodeType != XmlNodeType.Attribute) && (this.NodeType != XmlNodeType.Element)) {
Read();
return string.Empty;
}
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlWriter xtw = CreateWriterForInnerOuterXml(sw);
try {
if (this.NodeType == XmlNodeType.Attribute) {
xtw.WriteStartAttribute(this.Prefix, this.LocalName, this.NamespaceURI);
WriteAttributeValue(xtw);
xtw.WriteEndAttribute();
}
else {
xtw.WriteNode(this, false);
}
}
finally {
xtw.Close();
}
return sw.ToString();
}
private XmlWriter CreateWriterForInnerOuterXml(StringWriter sw) {
#if SILVERLIGHT // Removing dependency on XmlTextWriter
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
writerSettings.CheckCharacters = false;
writerSettings.NewLineHandling = NewLineHandling.None;
XmlWriter w = XmlWriter.Create(sw, writerSettings);
#else
XmlTextWriter w = new XmlTextWriter(sw);
// This is a V1 hack; we can put a custom implementation of ReadOuterXml on XmlTextReader/XmlValidatingReader
SetNamespacesFlag(w);
#endif
return w;
}
#if !SILVERLIGHT // Removing dependency on XmlTextWriter
void SetNamespacesFlag(XmlTextWriter xtw) {
XmlTextReader tr = this as XmlTextReader;
if (tr != null) {
xtw.Namespaces = tr.Namespaces;
}
else {
#pragma warning disable 618
XmlValidatingReader vr = this as XmlValidatingReader;
if (vr != null) {
xtw.Namespaces = vr.Namespaces;
}
}
#pragma warning restore 618
}
#endif
// Returns an XmlReader that will read only the current element and its descendants and then go to EOF state.
public virtual XmlReader ReadSubtree() {
if (NodeType != XmlNodeType.Element) {
throw new InvalidOperationException(Res.GetString(Res.Xml_ReadSubtreeNotOnElement));
}
return new XmlSubtreeReader(this);
}
// Returns true when the current node has any attributes.
public virtual bool HasAttributes {
get {
return AttributeCount > 0;
}
}
//
// IDisposable interface
//
public void Dispose() {
Dispose(true);
}
protected virtual void Dispose(bool disposing) { //the boolean flag may be used by subclasses to differentiate between disposing and finalizing
if (disposing && ReadState != ReadState.Closed) {
Close();
}
}
//
// Internal methods
//
// Validation support
#if !SILVERLIGHT
internal virtual XmlNamespaceManager NamespaceManager {
get {
return null;
}
}
#endif
static internal bool IsTextualNode(XmlNodeType nodeType) {
#if DEBUG
// This code verifies IsTextualNodeBitmap mapping of XmlNodeType to a bool specifying
// whether the node is 'textual' = Text, CDATA, Whitespace or SignificantWhitespace.
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.None)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Element)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Attribute)));
Debug.Assert(0 != (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Text)));
Debug.Assert(0 != (IsTextualNodeBitmap & (1 << (int)XmlNodeType.CDATA)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.EntityReference)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Entity)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.ProcessingInstruction)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Comment)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Document)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.DocumentType)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.DocumentFragment)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Notation)));
Debug.Assert(0 != (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Whitespace)));
Debug.Assert(0 != (IsTextualNodeBitmap & (1 << (int)XmlNodeType.SignificantWhitespace)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.EndElement)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.EndEntity)));
Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.XmlDeclaration)));
#endif
return 0 != (IsTextualNodeBitmap & (1 << (int)nodeType));
}
static internal bool CanReadContentAs(XmlNodeType nodeType) {
#if DEBUG
// This code verifies IsTextualNodeBitmap mapping of XmlNodeType to a bool specifying
// whether ReadContentAsXxx calls are allowed on his node type
Debug.Assert(0 == (CanReadContentAsBitmap & (1 << (int)XmlNodeType.None)));
Debug.Assert(0 == (CanReadContentAsBitmap & (1 << (int)XmlNodeType.Element)));
Debug.Assert(0 != (CanReadContentAsBitmap & (1 << (int)XmlNodeType.Attribute)));
Debug.Assert(0 != (CanReadContentAsBitmap & (1 << (int)XmlNodeType.Text)));
Debug.Assert(0 != (CanReadContentAsBitmap & (1 << (int)XmlNodeType.CDATA)));
Debug.Assert(0 != (CanReadContentAsBitmap & (1 << (int)XmlNodeType.EntityReference)));
Debug.Assert(0 == (CanReadContentAsBitmap & (1 << (int)XmlNodeType.Entity)));
Debug.Assert(0 != (CanReadContentAsBitmap & (1 << (int)XmlNodeType.ProcessingInstruction)));
Debug.Assert(0 != (CanReadContentAsBitmap & (1 << (int)XmlNodeType.Comment)));
Debug.Assert(0 == (CanReadContentAsBitmap & (1 << (int)XmlNodeType.Document)));
Debug.Assert(0 == (CanReadContentAsBitmap & (1 << (int)XmlNodeType.DocumentType)));
Debug.Assert(0 == (CanReadContentAsBitmap & (1 << (int)XmlNodeType.DocumentFragment)));
Debug.Assert(0 == (CanReadContentAsBitmap & (1 << (int)XmlNodeType.Notation)));
Debug.Assert(0 != (CanReadContentAsBitmap & (1 << (int)XmlNodeType.Whitespace)));
Debug.Assert(0 != (CanReadContentAsBitmap & (1 << (int)XmlNodeType.SignificantWhitespace)));
Debug.Assert(0 != (CanReadContentAsBitmap & (1 << (int)XmlNodeType.EndElement)));
Debug.Assert(0 != (CanReadContentAsBitmap & (1 << (int)XmlNodeType.EndEntity)));
Debug.Assert(0 == (CanReadContentAsBitmap & (1 << (int)XmlNodeType.XmlDeclaration)));
#endif
return 0 != (CanReadContentAsBitmap & (1 << (int)nodeType));
}
static internal bool HasValueInternal(XmlNodeType nodeType) {
#if DEBUG
// This code verifies HasValueBitmap mapping of XmlNodeType to a bool specifying
// whether the node can have a non-empty Value
Debug.Assert(0 == (HasValueBitmap & (1 << (int)XmlNodeType.None)));
Debug.Assert(0 == (HasValueBitmap & (1 << (int)XmlNodeType.Element)));
Debug.Assert(0 != (HasValueBitmap & (1 << (int)XmlNodeType.Attribute)));
Debug.Assert(0 != (HasValueBitmap & (1 << (int)XmlNodeType.Text)));
Debug.Assert(0 != (HasValueBitmap & (1 << (int)XmlNodeType.CDATA)));
Debug.Assert(0 == (HasValueBitmap & (1 << (int)XmlNodeType.EntityReference)));
Debug.Assert(0 == (HasValueBitmap & (1 << (int)XmlNodeType.Entity)));
Debug.Assert(0 != (HasValueBitmap & (1 << (int)XmlNodeType.ProcessingInstruction)));
Debug.Assert(0 != (HasValueBitmap & (1 << (int)XmlNodeType.Comment)));
Debug.Assert(0 == (HasValueBitmap & (1 << (int)XmlNodeType.Document)));
Debug.Assert(0 != (HasValueBitmap & (1 << (int)XmlNodeType.DocumentType)));
Debug.Assert(0 == (HasValueBitmap & (1 << (int)XmlNodeType.DocumentFragment)));
Debug.Assert(0 == (HasValueBitmap & (1 << (int)XmlNodeType.Notation)));
Debug.Assert(0 != (HasValueBitmap & (1 << (int)XmlNodeType.Whitespace)));
Debug.Assert(0 != (HasValueBitmap & (1 << (int)XmlNodeType.SignificantWhitespace)));
Debug.Assert(0 == (HasValueBitmap & (1 << (int)XmlNodeType.EndElement)));
Debug.Assert(0 == (HasValueBitmap & (1 << (int)XmlNodeType.EndEntity)));
Debug.Assert(0 != (HasValueBitmap & (1 << (int)XmlNodeType.XmlDeclaration)));
#endif
return 0 != (HasValueBitmap & (1 << (int)nodeType));
}
//
// Private methods
//
//SkipSubTree is called whenever validation of the skipped subtree is required on a reader with XsdValidation
private bool SkipSubtree() {
MoveToElement();
if (NodeType == XmlNodeType.Element && !IsEmptyElement) {
int depth = Depth;
while (Read() && depth < Depth) {
// Nothing, just read on
}
// consume end tag
if (NodeType == XmlNodeType.EndElement)
return Read();
}
else {
return Read();
}
return false;
}
internal void CheckElement(string localName, string namespaceURI) {
if (localName == null || localName.Length == 0) {
throw XmlConvert.CreateInvalidNameArgumentException(localName, "localName");
}
if (namespaceURI == null) {
throw new ArgumentNullException("namespaceURI");
}
if (NodeType != XmlNodeType.Element) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
}
if (LocalName != localName || NamespaceURI != namespaceURI) {
throw new XmlException(Res.Xml_ElementNotFoundNs, new string[2] { localName, namespaceURI }, this as IXmlLineInfo);
}
}
internal Exception CreateReadContentAsException(string methodName) {
return CreateReadContentAsException(methodName, NodeType, this as IXmlLineInfo);
}
internal Exception CreateReadElementContentAsException(string methodName) {
return CreateReadElementContentAsException(methodName, NodeType, this as IXmlLineInfo);
}
internal bool CanReadContentAs() {
return CanReadContentAs(this.NodeType);
}
static internal Exception CreateReadContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo lineInfo) {
return new InvalidOperationException(AddLineInfo(Res.GetString(Res.Xml_InvalidReadContentAs, new string[] { methodName, nodeType.ToString() }), lineInfo));
}
static internal Exception CreateReadElementContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo lineInfo) {
return new InvalidOperationException(AddLineInfo(Res.GetString(Res.Xml_InvalidReadElementContentAs, new string[] { methodName, nodeType.ToString() }), lineInfo));
}
static string AddLineInfo(string message, IXmlLineInfo lineInfo) {
if (lineInfo != null) {
string[] lineArgs = new string[2];
lineArgs[0] = lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture);
lineArgs[1] = lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture);
message += " " + Res.GetString(Res.Xml_ErrorPosition, lineArgs);
}
return message;
}
internal string InternalReadContentAsString() {
string value = string.Empty;
BufferBuilder sb = null;
do {
switch (this.NodeType) {
case XmlNodeType.Attribute:
return this.Value;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
// merge text content
if (value.Length == 0) {
value = this.Value;
}
else {
if (sb == null) {
sb = new BufferBuilder();
sb.Append(value);
}
sb.Append(this.Value);
}
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.EndEntity:
// skip comments, pis and end entity nodes
break;
case XmlNodeType.EntityReference:
if (this.CanResolveEntity) {
this.ResolveEntity();
break;
}
goto default;
case XmlNodeType.EndElement:
default:
goto ReturnContent;
}
} while ((this.AttributeCount != 0) ? this.ReadAttributeValue() : this.Read());
ReturnContent:
return (sb == null) ? value : sb.ToString();
}
private bool SetupReadElementContentAsXxx(string methodName) {
if (this.NodeType != XmlNodeType.Element) {
throw CreateReadElementContentAsException(methodName);
}
bool isEmptyElement = this.IsEmptyElement;
// move to content or beyond the empty element
this.Read();
if (isEmptyElement) {
return false;
}
XmlNodeType nodeType = this.NodeType;
if (nodeType == XmlNodeType.EndElement) {
this.Read();
return false;
}
else if (nodeType == XmlNodeType.Element) {
throw new XmlException(Res.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo);
}
return true;
}
private void FinishReadElementContentAsXxx() {
if (this.NodeType != XmlNodeType.EndElement) {
throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString());
}
this.Read();
}
internal bool IsDefaultInternal {
get {
#if SILVERLIGHT // Removing dependency on XmlSchema
return this.IsDefault;
#else
if (this.IsDefault) {
return true;
}
IXmlSchemaInfo schemaInfo = this.SchemaInfo;
if (schemaInfo != null && schemaInfo.IsDefault) {
return true;
}
return false;
#endif
}
}
#if !SILVERLIGHT
internal virtual IDtdInfo DtdInfo {
get {
return null;
}
}
#endif
#if !SILVERLIGHT // Needed only for XmlTextReader or XmlValidatingReader
internal static Encoding GetEncoding(XmlReader reader) {
XmlTextReaderImpl tri = GetXmlTextReaderImpl(reader);
return tri != null ? tri.Encoding : null;
}
#endif
internal static ConformanceLevel GetV1ConformanceLevel(XmlReader reader) {
XmlTextReaderImpl tri = GetXmlTextReaderImpl(reader);
return tri != null ? tri.V1ComformanceLevel : ConformanceLevel.Document;
}
private static XmlTextReaderImpl GetXmlTextReaderImpl(XmlReader reader) {
XmlTextReaderImpl tri = reader as XmlTextReaderImpl;
if (tri != null) {
return tri;
}
#if !SILVERLIGHT // Needed only for XmlTextReader or XmlValidatingReader
XmlTextReader tr = reader as XmlTextReader;
if (tr != null) {
return tr.Impl;
}
XmlValidatingReaderImpl vri = reader as XmlValidatingReaderImpl;
if (vri != null) {
return vri.ReaderImpl;
}
#pragma warning disable 618
XmlValidatingReader vr = reader as XmlValidatingReader;
#pragma warning restore 618
if (vr != null) {
return vr.Impl.ReaderImpl;
}
#endif
return null;
}
//
// Static methods for creating readers
//
// Creates an XmlReader for parsing XML from the given Uri.
#if !SILVERLIGHT
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
#endif
public static XmlReader Create(string inputUri) {
return XmlReader.Create(inputUri, (XmlReaderSettings)null, (XmlParserContext)null);
}
// Creates an XmlReader according to the settings for parsing XML from the given Uri.
#if !SILVERLIGHT
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
#endif
public static XmlReader Create(string inputUri, XmlReaderSettings settings) {
return XmlReader.Create(inputUri, settings, (XmlParserContext)null);
}
// Creates an XmlReader according to the settings and parser context for parsing XML from the given Uri.
#if !SILVERLIGHT
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
#endif
public static XmlReader Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext) {
if (settings == null) {
settings = new XmlReaderSettings();
}
return settings.CreateReader(inputUri, inputContext);
}
// Creates an XmlReader according for parsing XML from the given stream.
public static XmlReader Create(Stream input) {
return Create(input, (XmlReaderSettings)null, (string)string.Empty);
}
// Creates an XmlReader according to the settings for parsing XML from the given stream.
public static XmlReader Create(Stream input, XmlReaderSettings settings) {
return Create(input, settings, string.Empty);
}
// Creates an XmlReader according to the settings and base Uri for parsing XML from the given stream.
public static XmlReader Create(Stream input, XmlReaderSettings settings, String baseUri) {
if (settings == null) {
settings = new XmlReaderSettings();
}
return settings.CreateReader(input, null, (string)baseUri, null);
}
// Creates an XmlReader according to the settings and parser context for parsing XML from the given stream.
public static XmlReader Create(Stream input, XmlReaderSettings settings, XmlParserContext inputContext) {
if (settings == null) {
settings = new XmlReaderSettings();
}
return settings.CreateReader(input, null, (string)string.Empty, inputContext);
}
// Creates an XmlReader according for parsing XML from the given TextReader.
public static XmlReader Create(TextReader input) {
return Create(input, (XmlReaderSettings)null, (string)string.Empty);
}
// Creates an XmlReader according to the settings for parsing XML from the given TextReader.
public static XmlReader Create(TextReader input, XmlReaderSettings settings) {
return Create(input, settings, string.Empty);
}
// Creates an XmlReader according to the settings and baseUri for parsing XML from the given TextReader.
public static XmlReader Create(TextReader input, XmlReaderSettings settings, String baseUri) {
if (settings == null) {
settings = new XmlReaderSettings();
}
return settings.CreateReader(input, baseUri, null);
}
// Creates an XmlReader according to the settings and parser context for parsing XML from the given TextReader.
public static XmlReader Create(TextReader input, XmlReaderSettings settings, XmlParserContext inputContext) {
if (settings == null) {
settings = new XmlReaderSettings();
}
return settings.CreateReader(input, string.Empty, inputContext);
}
// Creates an XmlReader according to the settings wrapped over the given reader.
public static XmlReader Create(XmlReader reader, XmlReaderSettings settings) {
if (settings == null) {
settings = new XmlReaderSettings();
}
return settings.CreateReader(reader);
}
#if !SILVERLIGHT
// !!!!!!
// NOTE: This method is called via reflection from System.Data.dll and from Analysis Services in Yukon.
// Do not change its signature without notifying the appropriate teams!
// !!!!!!
internal static XmlReader CreateSqlReader(Stream input, XmlReaderSettings settings, XmlParserContext inputContext) {
if (input == null) {
throw new ArgumentNullException("input");
}
if (settings == null) {
settings = new XmlReaderSettings();
}
XmlReader reader;
// allocate byte buffer
byte[] bytes = new byte[CalcBufferSize(input)];
#if false
{
// catch the binary XML input and dump it into a local file (for debugging and testing purposes)
// create dump file name
string dumpFileNameBase = "~CreateSqlReaderInputDump";
string dumpFileName;
int i = 0;
do {
i++;
dumpFileName = Path.GetFullPath(string.Concat(dumpFileNameBase, i.ToString(), ".bmx"));
} while (File.Exists(dumpFileName));
// dump the input into the file
FileStream fs = new FileStream(dumpFileName, FileMode.Create, FileAccess.ReadWrite);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) {
fs.Write(buffer, 0, bytesRead);
}
fs.Seek(0, SeekOrigin.Begin);
// make sure it will get closed
if (settings.CloseInput) {
input.Close();
}
input = fs;
settings = settings.Clone();
settings.CloseInput = true;
}
#endif
int byteCount = 0;
int read;
do {
read = input.Read(bytes, byteCount, bytes.Length - byteCount);
byteCount += read;
} while (read > 0 && byteCount < 2);
// create text or binary XML reader depenting on the stream first 2 bytes
if (byteCount >= 2 && (bytes[0] == 0xdf && bytes[1] == 0xff)) {
if ( inputContext != null )
throw new ArgumentException(Res.GetString(Res.XmlBinary_NoParserContext), "inputContext");
reader = new XmlSqlBinaryReader(input, bytes, byteCount, string.Empty, settings.CloseInput, settings);
}
else {
reader = new XmlTextReaderImpl(input, bytes, byteCount, settings, null, string.Empty, inputContext, settings.CloseInput);
}
// wrap with validating reader
if ( settings.ValidationType != ValidationType.None ) {
reader = settings.AddValidation( reader );
}
if (settings.Async) {
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
#endif
internal static int CalcBufferSize(Stream input) {
// determine the size of byte buffer
int bufferSize = DefaultBufferSize;
if (input.CanSeek) {
long len = input.Length;
if (len < bufferSize) {
bufferSize = checked((int)len);
}
else if (len > MaxStreamLengthForDefaultBufferSize) {
bufferSize = BiggerBufferSize;
}
}
// return the byte buffer size
return bufferSize;
}
#if !SILVERLIGHT // This is used for displaying the state of the XmlReader in Watch/Locals windows in the Visual Studio during debugging
private object debuggerDisplayProxy { get { return new XmlReaderDebuggerDisplayProxy(this); } }
[DebuggerDisplay("{ToString()}")]
struct XmlReaderDebuggerDisplayProxy {
XmlReader reader;
internal XmlReaderDebuggerDisplayProxy( XmlReader reader ) {
this.reader = reader;
}
public override string ToString() {
XmlNodeType nt = reader.NodeType;
string result = nt.ToString();
switch ( nt ) {
case XmlNodeType.Element:
case XmlNodeType.EndElement:
case XmlNodeType.EntityReference:
case XmlNodeType.EndEntity:
result += ", Name=\"" + reader.Name + '"';
break;
case XmlNodeType.Attribute:
case XmlNodeType.ProcessingInstruction:
result += ", Name=\"" + reader.Name + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay( reader.Value ) + '"';
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Comment:
case XmlNodeType.XmlDeclaration:
case XmlNodeType.CDATA:
result += ", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay( reader.Value ) + '"';
break;
case XmlNodeType.DocumentType:
result += ", Name=\"" + reader.Name + "'";
result += ", SYSTEM=\"" + reader.GetAttribute( "SYSTEM" ) + '"';
result += ", PUBLIC=\"" + reader.GetAttribute( "PUBLIC" ) + '"';
result += ", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay( reader.Value ) + '"';
break;
}
return result;
}
}
#endif
}
}
|