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
|
//------------------------------------------------------------------------------
// <copyright file="XmlWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
//------------------------------------------------------------------------------
using System;
using System.IO;
using System.Text;
#if !SILVERLIGHT
using System.Xml.XPath;
#endif
using System.Xml.Schema;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Versioning;
namespace System.Xml {
// Specifies the state of the XmlWriter.
public enum WriteState {
// Nothing has been written yet.
Start,
// Writing the prolog.
Prolog,
// Writing a the start tag for an element.
Element,
// Writing an attribute value.
Attribute,
// Writing element content.
Content,
// XmlWriter is closed; Close has been called.
Closed,
// Writer is in error state.
Error,
};
// Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents
// that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification.
public abstract partial class XmlWriter : IDisposable {
// Helper buffer for WriteNode(XmlReader, bool)
char[] writeNodeBuffer;
// Constants
const int WriteNodeBufferSize = 1024;
// Returns the settings describing the features of the the writer. Returns null for V1 XmlWriters (XmlTextWriter).
public virtual XmlWriterSettings Settings {
get {
return null;
}
}
// Write methods
// Writes out the XML declaration with the version "1.0".
public abstract void WriteStartDocument();
//Writes out the XML declaration with the version "1.0" and the speficied standalone attribute.
public abstract void WriteStartDocument(bool standalone);
//Closes any open elements or attributes and puts the writer back in the Start state.
public abstract void WriteEndDocument();
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
public abstract void WriteDocType(string name, string pubid, string sysid, string subset);
// Writes out the specified start tag and associates it with the given namespace.
public void WriteStartElement(string localName, string ns) {
WriteStartElement(null, localName, ns);
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
public abstract void WriteStartElement(string prefix, string localName, string ns);
// Writes out a start tag with the specified local name with no namespace.
public void WriteStartElement(string localName) {
WriteStartElement(null, localName, (string)null);
}
// Closes one element and pops the corresponding namespace scope.
public abstract void WriteEndElement();
// Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>.
public abstract void WriteFullEndElement();
// Writes out the attribute with the specified LocalName, value, and NamespaceURI.
#if !SILVERLIGHT
#endif
public void WriteAttributeString(string localName, string ns, string value) {
WriteStartAttribute(null, localName, ns);
WriteString(value);
WriteEndAttribute();
}
// Writes out the attribute with the specified LocalName and value.
public void WriteAttributeString(string localName, string value) {
WriteStartAttribute(null, localName, (string)null);
WriteString(value);
WriteEndAttribute();
}
// Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
public void WriteAttributeString(string prefix, string localName, string ns, string value) {
WriteStartAttribute(prefix, localName, ns);
WriteString(value);
WriteEndAttribute();
}
// Writes the start of an attribute.
public void WriteStartAttribute(string localName, string ns) {
WriteStartAttribute(null, localName, ns);
}
// Writes the start of an attribute.
public abstract void WriteStartAttribute(string prefix, string localName, string ns);
// Writes the start of an attribute.
public void WriteStartAttribute(string localName) {
WriteStartAttribute(null, localName, (string)null);
}
// Closes the attribute opened by WriteStartAttribute call.
public abstract void WriteEndAttribute();
// Writes out a <![CDATA[...]]>; block containing the specified text.
public abstract void WriteCData(string text);
// Writes out a comment <!--...-->; containing the specified text.
public abstract void WriteComment(string text);
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
public abstract void WriteProcessingInstruction(string name, string text);
// Writes out an entity reference as follows: "&"+name+";".
public abstract void WriteEntityRef(string name);
// Forces the generation of a character entity for the specified Unicode character value.
public abstract void WriteCharEntity(char ch);
// Writes out the given whitespace.
public abstract void WriteWhitespace(string ws);
// Writes out the specified text content.
public abstract void WriteString(string text);
// Write out the given surrogate pair as an entity reference.
public abstract void WriteSurrogateCharEntity(char lowChar, char highChar);
// Writes out the specified text content.
public abstract void WriteChars(char[] buffer, int index, int count);
// Writes raw markup from the given character buffer.
public abstract void WriteRaw(char[] buffer, int index, int count);
// Writes raw markup from the given string.
public abstract void WriteRaw(string data);
// Encodes the specified binary bytes as base64 and writes out the resulting text.
public abstract void WriteBase64(byte[] buffer, int index, int count);
// Encodes the specified binary bytes as binhex and writes out the resulting text.
public virtual void WriteBinHex(byte[] buffer, int index, int count) {
BinHexEncoder.Encode(buffer, index, count, this);
}
// Returns the state of the XmlWriter.
public abstract WriteState WriteState { get; }
// Closes the XmlWriter and the underlying stream/TextReader (if Settings.CloseOutput is true).
public virtual void Close() { }
// Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader.
public abstract void Flush();
// Returns the closest prefix defined in the current namespace scope for the specified namespace URI.
public abstract string LookupPrefix(string ns);
// Gets an XmlSpace representing the current xml:space scope.
public virtual XmlSpace XmlSpace {
get {
return XmlSpace.Default;
}
}
// Gets the current xml:lang scope.
public virtual string XmlLang {
get {
return string.Empty;
}
}
// Scalar Value Methods
// Writes out the specified name, ensuring it is a valid NmToken according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual void WriteNmToken(string name) {
if (name == null || name.Length == 0) {
throw new ArgumentException(Res.GetString(Res.Xml_EmptyName));
}
WriteString(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException));
}
// Writes out the specified name, ensuring it is a valid Name according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual void WriteName(string name) {
WriteString(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException));
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
public virtual void WriteQualifiedName(string localName, string ns) {
if (ns != null && ns.Length > 0) {
string prefix = LookupPrefix(ns);
if (prefix == null) {
throw new ArgumentException(Res.GetString(Res.Xml_UndefNamespace, ns));
}
WriteString(prefix);
WriteString(":");
}
WriteString(localName);
}
// Writes out the specified value.
public virtual void WriteValue(object value) {
if (value == null) {
throw new ArgumentNullException("value");
}
#if SILVERLIGHT
WriteString(XmlUntypedStringConverter.Instance.ToString(value, null));
#else
WriteString(XmlUntypedConverter.Untyped.ToString(value, null));
#endif
}
// Writes out the specified value.
public virtual void WriteValue(string value) {
if (value == null) {
return;
}
WriteString(value);
}
// Writes out the specified value.
public virtual void WriteValue(bool value) {
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(DateTime value) {
WriteString(XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind));
}
// Writes out the specified value.
public virtual void WriteValue(DateTimeOffset value) {
// Under Win8P, WriteValue(DateTime) will invoke this overload, but custom writers
// might not have implemented it. This base implementation should call WriteValue(DateTime).
// The following conversion results in the same string as calling ToString with DateTimeOffset.
if (value.Offset != TimeSpan.Zero) {
WriteValue(value.LocalDateTime);
}
else {
WriteValue(value.UtcDateTime);
}
}
// Writes out the specified value.
public virtual void WriteValue(double value) {
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(float value) {
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(decimal value) {
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(int value) {
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(long value) {
WriteString(XmlConvert.ToString(value));
}
// XmlReader Helper Methods
// Writes out all the attributes found at the current position in the specified XmlReader.
public virtual void WriteAttributes(XmlReader reader, bool defattr) {
if (null == reader) {
throw new ArgumentNullException("reader");
}
if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration) {
if (reader.MoveToFirstAttribute()) {
WriteAttributes(reader, defattr);
reader.MoveToElement();
}
}
else if (reader.NodeType != XmlNodeType.Attribute) {
throw new XmlException(Res.Xml_InvalidPosition, string.Empty);
}
else {
do {
// we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault.
// If either of these is true and defattr=false, we should not write the attribute out
if (defattr || !reader.IsDefaultInternal) {
WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
while (reader.ReadAttributeValue()) {
if (reader.NodeType == XmlNodeType.EntityReference) {
WriteEntityRef(reader.Name);
}
else {
WriteString(reader.Value);
}
}
WriteEndAttribute();
}
}
while (reader.MoveToNextAttribute());
}
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
public virtual void WriteNode(XmlReader reader, bool defattr) {
if (null == reader) {
throw new ArgumentNullException("reader");
}
bool canReadChunk = reader.CanReadValueChunk;
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do {
switch (reader.NodeType) {
case XmlNodeType.Element:
WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
WriteAttributes(reader, defattr);
if (reader.IsEmptyElement) {
WriteEndElement();
break;
}
break;
case XmlNodeType.Text:
if (canReadChunk) {
if (writeNodeBuffer == null) {
writeNodeBuffer = new char[WriteNodeBufferSize];
}
int read;
while ((read = reader.ReadValueChunk(writeNodeBuffer, 0, WriteNodeBufferSize)) > 0) {
this.WriteChars(writeNodeBuffer, 0, read);
}
}
else {
WriteString(reader.Value);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
WriteWhitespace(reader.Value);
break;
case XmlNodeType.CDATA:
WriteCData(reader.Value);
break;
case XmlNodeType.EntityReference:
WriteEntityRef(reader.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.DocumentType:
WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
break;
case XmlNodeType.Comment:
WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
WriteFullEndElement();
break;
}
} while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
#if !SILVERLIGHT // Removing dependency on XPathNavigator
// Copies the current node from the given XPathNavigator to the writer (including child nodes).
public virtual void WriteNode(XPathNavigator navigator, bool defattr) {
if (navigator == null) {
throw new ArgumentNullException("navigator");
}
int iLevel = 0;
navigator = navigator.Clone();
while (true) {
bool mayHaveChildren = false;
XPathNodeType nodeType = navigator.NodeType;
switch (nodeType) {
case XPathNodeType.Element:
WriteStartElement(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI);
// Copy attributes
if (navigator.MoveToFirstAttribute()) {
do {
IXmlSchemaInfo schemaInfo = navigator.SchemaInfo;
if (defattr || (schemaInfo == null || !schemaInfo.IsDefault)) {
WriteStartAttribute(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI);
// copy string value to writer
WriteString(navigator.Value);
WriteEndAttribute();
}
} while (navigator.MoveToNextAttribute());
navigator.MoveToParent();
}
// Copy namespaces
if (navigator.MoveToFirstNamespace(XPathNamespaceScope.Local)) {
WriteLocalNamespaces(navigator);
navigator.MoveToParent();
}
mayHaveChildren = true;
break;
case XPathNodeType.Attribute:
// do nothing on root level attribute
break;
case XPathNodeType.Text:
WriteString(navigator.Value);
break;
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
WriteWhitespace(navigator.Value);
break;
case XPathNodeType.Root:
mayHaveChildren = true;
break;
case XPathNodeType.Comment:
WriteComment(navigator.Value);
break;
case XPathNodeType.ProcessingInstruction:
WriteProcessingInstruction(navigator.LocalName, navigator.Value);
break;
case XPathNodeType.Namespace:
// do nothing on root level namespace
break;
default:
Debug.Assert(false);
break;
}
if (mayHaveChildren) {
// If children exist, move down to next level
if (navigator.MoveToFirstChild()) {
iLevel++;
continue;
}
else {
// EndElement
if (navigator.NodeType == XPathNodeType.Element) {
if (navigator.IsEmptyElement) {
WriteEndElement();
}
else {
WriteFullEndElement();
}
}
}
}
// No children
while (true) {
if (iLevel == 0) {
// The entire subtree has been copied
return;
}
if (navigator.MoveToNext()) {
// Found a sibling, so break to outer loop
break;
}
// No siblings, so move up to previous level
iLevel--;
navigator.MoveToParent();
// EndElement
if (navigator.NodeType == XPathNodeType.Element)
WriteFullEndElement();
}
}
}
#endif
// Element Helper Methods
// Writes out an element with the specified name containing the specified string value.
public void WriteElementString(string localName, String value) {
WriteElementString(localName, null, value);
}
// Writes out an attribute with the specified name, namespace URI and string value.
public void WriteElementString(string localName, String ns, String value) {
WriteStartElement(localName, ns);
if (null != value && 0 != value.Length) {
WriteString(value);
}
WriteEndElement();
}
// Writes out an attribute with the specified name, namespace URI, and string value.
public void WriteElementString(string prefix, String localName, String ns, String value) {
WriteStartElement(prefix, localName, ns);
if (null != value && 0 != value.Length) {
WriteString(value);
}
WriteEndElement();
}
public void Dispose() {
Dispose(true);
}
// Dispose the underline stream objects (calls Close on the XmlWriter)
protected virtual void Dispose(bool disposing) {
if (disposing && WriteState != WriteState.Closed) {
Close();
}
}
#if !SILVERLIGHT // Removing dependency on XPathNavigator
// Copy local namespaces on the navigator's current node to the raw writer. The namespaces are returned by the navigator in reversed order.
// The recursive call reverses them back.
private void WriteLocalNamespaces(XPathNavigator nsNav) {
string prefix = nsNav.LocalName;
string ns = nsNav.Value;
if (nsNav.MoveToNextNamespace(XPathNamespaceScope.Local)) {
WriteLocalNamespaces(nsNav);
}
if (prefix.Length == 0) {
WriteAttributeString(string.Empty, "xmlns", XmlReservedNs.NsXmlNs, ns);
}
else {
WriteAttributeString("xmlns", prefix, XmlReservedNs.NsXmlNs, ns);
}
}
#endif
//
// Static methods for creating writers
//
#if !SILVERLIGHT
// Creates an XmlWriter for writing into the provided file.
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public static XmlWriter Create(string outputFileName) {
return Create(outputFileName, null);
}
// Creates an XmlWriter for writing into the provided file with the specified settings.
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public static XmlWriter Create(string outputFileName, XmlWriterSettings settings) {
if (settings == null) {
settings = new XmlWriterSettings();
}
return settings.CreateWriter(outputFileName);
}
#endif
// Creates an XmlWriter for writing into the provided stream.
public static XmlWriter Create(Stream output) {
return Create(output, null);
}
// Creates an XmlWriter for writing into the provided stream with the specified settings.
public static XmlWriter Create(Stream output, XmlWriterSettings settings) {
if (settings == null) {
settings = new XmlWriterSettings();
}
return settings.CreateWriter(output);
}
// Creates an XmlWriter for writing into the provided TextWriter.
public static XmlWriter Create(TextWriter output) {
return Create(output, null);
}
// Creates an XmlWriter for writing into the provided TextWriter with the specified settings.
public static XmlWriter Create(TextWriter output, XmlWriterSettings settings) {
if (settings == null) {
settings = new XmlWriterSettings();
}
return settings.CreateWriter(output);
}
// Creates an XmlWriter for writing into the provided StringBuilder.
public static XmlWriter Create(StringBuilder output) {
return Create(output, null);
}
// Creates an XmlWriter for writing into the provided StringBuilder with the specified settings.
public static XmlWriter Create(StringBuilder output, XmlWriterSettings settings) {
if (settings == null) {
settings = new XmlWriterSettings();
}
if (output == null) {
throw new ArgumentNullException("output");
}
return settings.CreateWriter(new StringWriter(output, CultureInfo.InvariantCulture));
}
// Creates an XmlWriter wrapped around the provided XmlWriter with the default settings.
public static XmlWriter Create(XmlWriter output) {
return Create(output, null);
}
// Creates an XmlWriter wrapped around the provided XmlWriter with the specified settings.
public static XmlWriter Create(XmlWriter output, XmlWriterSettings settings) {
if (settings == null) {
settings = new XmlWriterSettings();
}
return settings.CreateWriter(output);
}
}
}
|