Beispiel #1
0
        /// <summary>
        /// Generates a string representation of the given <paramref name="obj"/> using the default
        /// <see cref="XmlFormatOptions"/>. The output will contain one element for every readable
        /// property on <paramref name="obj"/> and process reference properties (other than strings)
        /// recursively. This method does not handle cyclic references - passing in such an object
        /// graph will cause an infinite loop.
        /// </summary>
        /// <param name="obj">The object to convert to XML.</param>
        /// <param name="options"></param>
        /// <returns>A string containing the generated XML data.</returns>
        public static string ToXml(this object obj, XmlFormatOptions options)
        {
            bool   newLineAfterElement = (options & XmlFormatOptions.NewLineAfterElement) == XmlFormatOptions.NewLineAfterElement;
            string afterElement        = newLineAfterElement ? Environment.NewLine : String.Empty;
            bool   tabIndent           = (options & XmlFormatOptions.UseSpaces) != XmlFormatOptions.UseSpaces;
            string indent    = tabIndent ? "\t" : "    ";
            bool   addHeader = (options & XmlFormatOptions.AddHeader) == XmlFormatOptions.AddHeader;
            string header    = addHeader ? "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine : string.Empty;

            return(ToXml(obj, header, afterElement, indent, String.Empty));
        }
        /// <summary>
        /// Formats an XML string applying specific encoding and formatting options.
        /// </summary>
        /// <param name="value">String to which this extension method applies.</param>
        /// <param name="encoding">
        /// Encoding use for the transformed output. Use the same encoding as the target device to preserve all content, e.g. HTTP request encoding or database
        /// XML encoding (Unicode for SQL Server).
        /// </param>
        /// <param name="options">Formatting options.</param>
        /// <returns>Formatted string.</returns>
        public static string FormatXml(this string value, Encoding encoding, XmlFormatOptions options = XmlFormatOptions.Indent | XmlFormatOptions.Trim)
        {
            // Validate
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            // Format...
            try
            {
                // Create XML settings from formatting options
                var outputSettings = new XmlWriterSettings
                {
                    OmitXmlDeclaration = (options & XmlFormatOptions.OmitXmlDeclaration) != 0,
                    Encoding           = encoding,
                    Indent             = (options & XmlFormatOptions.Indent) != 0,
                    ConformanceLevel   = ConformanceLevel.Fragment,
                    NewLineHandling    = NewLineHandling.Replace
                };
                var inputSettings = new XmlReaderSettings
                {
                    IgnoreWhitespace = (options & (XmlFormatOptions.Trim | XmlFormatOptions.Indent)) != 0,
                    IgnoreComments   = (options & XmlFormatOptions.OmitComments) != 0,
                    ConformanceLevel = ConformanceLevel.Fragment
                };

                // Decide which transform to use for best performance
                XslCompiledTransform transform;
                if ((options & XmlFormatOptions.OmitNamespaces) != 0)
                {
                    transform = FormatXmlAnyTransform;
                }
                else if ((options & XmlFormatOptions.Trim) != 0)
                {
                    transform = FormatXmlTrimTransform;
                }
                else
                {
                    transform = FormatXmlCopyTransform;
                }

                // Apply transform and switch to Unicode encoding
                var buffer = new StringBuilder();
                using (var reader = XmlReader.Create(new StringReader(value), inputSettings))
                    using (var writer = XmlWriter.Create(buffer, outputSettings))
                    {
                        if ((options & XmlFormatOptions.OmitXmlDeclaration) == 0)
                        {
                            // Add XML declaration manually when required because it is always removed when we support fragments
                            writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"" + encoding.BodyName + "\"");
                        }
                        transform.Transform(reader, null, writer);
                    }

                // Return result
                return(buffer.ToString());
            }
            catch
            {
                // Ignore error if specified
                if ((options | XmlFormatOptions.IgnoreErrors) != 0)
                {
                    return(value);
                }
                throw;
            }
        }
 public static string Serialize(this XmlSerializer serializer, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id, XmlFormatOptions options)
 {
     return(XmlHelper.ReformatXml(serializer.Serialize(o, namespaces, encodingStyle, id), options));
 }
 public static string Serialize(this XmlSerializer serializer, object o, XmlFormatOptions options)
 {
     return(XmlHelper.ReformatXml(serializer.Serialize(o), options));
 }