IXmlSerializable.WriteXml(XmlWriter) Method

Definition

Converts an object into its XML representation.

C#
public void WriteXml(System.Xml.XmlWriter writer);

Parameters

writer
XmlWriter

The XmlWriter stream to which the object is serialized.

Examples

The following example illustrates an implementation of the WriteXml method.

C#
public void WriteXml (XmlWriter writer)
{
    writer.WriteString(personName);
}

The following example illustrates the use of the XmlSerializer class to serialize this object.

C#
using System;
using System.Xml;
using System.Xml.Serialization;

public class Writer {

  public static void Main() {

    // Create a person object.
    Person fred = new Person("Fred Flintstone");

    // Serialize the object to a file.
    XmlTextWriter writer = new XmlTextWriter("test.xml", null);
    XmlSerializer serializer = new XmlSerializer(typeof(Person));
    serializer.Serialize(writer, fred);
  }
}

Remarks

The WriteXml implementation you provide should write out the XML representation of the object. The framework writes a wrapper element and positions the XML writer after its start. Your implementation may write its contents, including child elements. The framework then closes the wrapper element.

Write sufficient information to the XmlWriter stream to allow the ReadXml method to reconstitute your object.

For example, if your object state includes an array variable, be sure to write the length of the array, or use a parent element to contain the elements that describe the array values, so that you know how many values to read when the object is reconstituted.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0