XmlWriter.Close Method
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
When overridden in a derived class, closes this stream and the underlying stream.
Assembly: System.Xml (in System.Xml.dll)
| Exception | Condition |
|---|---|
| InvalidOperationException | A call is made to write more output after Close has been called or the result of this call is an invalid XML document. |
Any elements or attributes left open are automatically closed.
Note: |
|---|
When you use the XmlWriter methods to output XML, the elements and attributes will not be written until you call the Close method. |
The following example navigates through the stream to determine the current node type, and then uses XmlWriter to output the XmlReader content.
StringBuilder output = new StringBuilder(); String xmlString = @"<?xml version='1.0'?> <!-- This is a sample XML document --> <Items> <Item>test with a child element <more/> stuff</Item> </Items>"; // Create an XmlReader using (XmlReader reader = XmlReader.Create(new StringReader(xmlString))) { XmlWriterSettings ws = new XmlWriterSettings(); ws.Indent = true; using (XmlWriter writer = XmlWriter.Create(output, ws)) { // Parse the file and display each of the nodes. while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: writer.WriteStartElement(reader.Name); break; case XmlNodeType.Text: writer.WriteString(reader.Value); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: writer.WriteProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.Comment: writer.WriteComment(reader.Value); break; case XmlNodeType.EndElement: writer.WriteFullEndElement(); break; } } } } OutputTextBlock.Text = output.ToString();
Note: