Serialization
This guide explains how to use the XmlPrime serializer.
Overview
The XdmSerializerXdmSerializerXdmSerializer is an implementation of XSLT 2.0 and XQuery 1.0 Serialization. It is similar to XmlWriterXmlWriterXmlWriter except for the following differences.
- XdmSerializerXdmSerializerXdmSerializer supports the full set of parameters as specified in XSLT 2.0 and XQuery 1.0 Serialization.
- XdmSerializerXdmSerializerXdmSerializer operates on sequences of items (both nodes and atomic values), rather than an XML token stream.
Creating a serializer
The XdmSerializationSettingsXdmSerializationSettingsXdmSerializationSettings class exposes all the different serialization settings.
If you are serializing the result of an XQuery program, then the
serialization settings that should be used are specified in
XQuery.SerializationSettingsXQuery.SerializationSettingsXQuery::SerializationSettings.
The settings specified by the query are the settings that were
specified in
XQuerySettings.SerializationSettingsXQuerySettings.SerializationSettingsXQuerySettings::SerializationSettings
augmented by any relevant declare option
declarations in the query itself.
The serialization settings are then passed to the constructor of XdmSerializerXdmSerializerXdmSerializer to create a serializer with the specified settings.
The following code shows how to create a serializer that produces indented HTML.
XdmSerializationSettings serializationSettings = new XdmSerializationSettings(XdmSerializationSettings.HtmlOutputMethod); settings.Indent = true; XdmSerializer serializer = new XdmSerializer(settings);
Serializing a document
Once you have constructed a serializer, you can use it to serialize an
item or item sequence to a document. This is done via the
XdmSerializer.SerializeXdmSerializer.SerializeXdmSerializer::Serialize
method. The serializer does the job of serializing nodes and writing
them out to a stream. Here is an example of saving the result of a
query (stored in query
) to a file (out.xml).
XPathItemCollection result = query.Evaluate(...); using (Stream stream = File.Create("out.xml")) { serializer.Serialize(result, stream); }