예제 #1
0
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = "application/xml";

            using (var txtWriter = new Utf8StringWriter())
            {
                var xmlWriter = XmlWriter.Create(txtWriter, new XmlWriterSettings
                {
                    Encoding = Encoding.UTF8,
                    Indent = true,
                    OmitXmlDeclaration = false
                });

                // Write the Processing Instruction node.
                var xsltHeader = string.Format("type=\"text/xsl\" href=\"{0}\"", _model.RootBlogNode.UrlWithDomain().EnsureEndsWith('/') + "rss/xslt");
                xmlWriter.WriteProcessingInstruction("xml-stylesheet", xsltHeader);

                var formatter = _feed.GetRss20Formatter();
                formatter.WriteTo(xmlWriter);

                xmlWriter.Flush();

                context.HttpContext.Response.Write(txtWriter.ToString());
            }
        }
예제 #2
0
파일: Xml.cs 프로젝트: rgatkinson/nadir
 string XMLSerialize(object oResult)
 // http://msdn.microsoft.com/en-us/library/58a18dwa(v=VS.100).aspx
     {
     IXmlWritable wResult = oResult as IXmlWritable;
     if (wResult != null)
         {
         XmlSerializer ser = new XmlSerializer(typeof(XmlElement));
         TextWriter writer = new Utf8StringWriter();
         XmlContext context = new XmlContext();
         //
         context.Document = new XmlDocument();
         //
         XmlElement wElement = wResult.ToXml(context);;
         //
         XmlElement rootElement = context.CreateElement("Root");
         rootElement.Attributes.Append(context.CreateAttribute("randSeed", MiscUtil.RandSeed));
         rootElement.AppendChild(wElement);
         //
         context.Document.AppendChild(rootElement);
         //
         ser.Serialize(writer, context.Document);
         writer.Close();
         return writer.ToString();
         }
     return null;
     }
예제 #3
0
        /// <summary>
        /// Returns the document encoded with UTF-8. 
        /// </summary>
        public static string ToUtf8DocumentString(this XDocument doc)
        {
            var writer = new Utf8StringWriter();
            doc.Declaration = new XDeclaration("1.0", "utf-8", null);
            doc.Save(writer, SaveOptions.None);

            return writer.ToString();
        }
        String Serialize()
        {
            // Additional information: Could not load file or assembly 'CyPhy2CAD_CSharp.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8adbc89a2d94c2a4' or one of its dependencies. The system cannot find the file specified.
            XmlSerializer xs = new XmlSerializer(this.GetType()); // n.b. An exception is expected here. It is caught inside of the .NET framework code
            StringWriter sw = new Utf8StringWriter();       //StringWriter sw = new StringWriter();

            xs.Serialize(sw, this);
            return sw.ToString();
        }
예제 #5
0
			public StudyXmlNode(XmlNode node)
			{
				using (TextWriter writer = new Utf8StringWriter())
				{
					using (XmlWriter xmlWriter = XmlWriter.Create(writer,new XmlWriterSettings(){ConformanceLevel = ConformanceLevel.Fragment}))
					{
						node.WriteTo(xmlWriter);
					}
					XmlElementFragment = writer.ToString();
				}
			}
예제 #6
0
파일: ADIFIO.cs 프로젝트: rlmobley/ADIF.net
        public static string ConvertToADX(ADIFData data)
        {
            var serializer = new XmlSerializer(typeof(ADIFData));
            var ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            using (var sw = new Utf8StringWriter())
            {
                serializer.Serialize(sw, data, ns);
                return sw.ToString();
            }
        }
예제 #7
0
    internal static bool Save <T>(T data, string saveFilePath)
    {
        var ser = new XmlSerializer(typeof(T));

        using (var sw = new StreamWriter(saveFilePath, false, Encoding.UTF8))
        {
            using (var usw = new Utf8StringWriter())
            {
                ser.Serialize(usw, data);
                sw.Write(usw.ToString());
            }
        }
        return(true);
    }
예제 #8
0
        public static string CreateAnalyzersXml()
        {
            FieldInfo[] fieldInfos = typeof(DiagnosticDescriptors).GetFields(BindingFlags.Public | BindingFlags.Static);

            var doc = new XDocument();

            var root = new XElement("Analyzers");

            foreach (FieldInfo fieldInfo in fieldInfos.OrderBy(f => ((DiagnosticDescriptor)f.GetValue(null)).Id))
            {
                if (fieldInfo.Name.EndsWith("FadeOut"))
                {
                    continue;
                }

                var descriptor = (DiagnosticDescriptor)fieldInfo.GetValue(null);

                var analyzer = new AnalyzerDescriptor(
                    fieldInfo.Name,
                    descriptor.Title.ToString(),
                    descriptor.Id,
                    descriptor.Category,
                    descriptor.DefaultSeverity.ToString(),
                    descriptor.IsEnabledByDefault,
                    descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary),
                    fieldInfos.Any(f => f.Name == fieldInfo.Name + "FadeOut"));

                root.Add(new XElement(
                             "Analyzer",
                             new XAttribute("Identifier", analyzer.Identifier),
                             new XElement("Id", analyzer.Id),
                             new XElement("Title", analyzer.Title),
                             new XElement("Category", analyzer.Category),
                             new XElement("DefaultSeverity", analyzer.DefaultSeverity),
                             new XElement("IsEnabledByDefault", analyzer.IsEnabledByDefault),
                             new XElement("SupportsFadeOut", analyzer.SupportsFadeOut),
                             new XElement("SupportsFadeOutAnalyzer", analyzer.SupportsFadeOutAnalyzer)
                             ));
            }

            doc.Add(root);

            using (var sw = new Utf8StringWriter())
            {
                doc.Save(sw);

                return(sw.ToString());
            }
        }
예제 #9
0
        public override string GetXmlRepresentation()
        {
            XmlSerializer xsSubmit = new XmlSerializer(typeof(RSSFeed));
            string        xml      = "";

            using (var sww = new Utf8StringWriter())
            {
                using (XmlWriter writer = XmlWriter.Create(sww))
                {
                    xsSubmit.Serialize(writer, this);
                    xml = sww.ToString();
                }
            }
            return(xml);
        }
예제 #10
0
 /// <summary>
 /// Toes the XML.
 /// </summary>
 /// <param name="data">The data.</param>
 /// <param name="type">The type.</param>
 /// <returns></returns>
 public static string ToXml(this object data, Type type)
 {
     try
     {
         using (var stringWriter = new Utf8StringWriter())
         {
             GetSerializer(type).Serialize(stringWriter, data);
             return(stringWriter.ToString());
         }
     }
     catch (Exception ex)
     {
         throw new SerializationException($"Error during serialization {type}", ex);
     }
 }
예제 #11
0
        static ProjectFileHook()
        {
            ProjectFilesGenerator.ProjectFileGeneration += (string name, string content) =>
            {
                var document = XDocument.Parse(content);

                RemoveFileFromProject(document, @"Assets\System.Data.dll");
                RemoveHintPathFromReference(document, "System.Data");

                var str = new Utf8StringWriter();
                document.Save(str);

                return(str.ToString());
            };
        }
예제 #12
0
파일: Factura.cs 프로젝트: WinstonR96/SPRB
 public string ToXML()
 {
     try
     {
         var stringwriter = new Utf8StringWriter();
         var serializer   = new XmlSerializer(this.GetType());
         serializer.Serialize(stringwriter, this);
         return(stringwriter.ToString());
     }
     catch (Exception e)
     {
         Console.WriteLine("error: " + e.Message + "\n" + e);
         return(null);
     }
 }
예제 #13
0
        public static string Serialize <T>(T source, XmlWriterSettings writerSettings)
        {
            var serializerNamespaces = new XmlSerializerNamespaces();

            serializerNamespaces.Add(string.Empty, string.Empty);

            var serializer = new XmlSerializer(typeof(T));

            using (var stringWriter = new Utf8StringWriter())
                using (var xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
                {
                    serializer.Serialize(xmlWriter, source, serializerNamespaces);
                    return(stringWriter.ToString());
                }
        }
예제 #14
0
        /// <summary>
        /// Executes the specified result.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        protected override bool Execute(IIntegrationResult result)
        {
            result.BuildProgressInformation.SignalStartRunTask(!string.IsNullOrEmpty(Description) ? Description : "Writing Modifications");

            XmlSerializer serializer = new XmlSerializer(typeof(Modification[]));
            StringWriter  writer     = new Utf8StringWriter();

            serializer.Serialize(writer, result.Modifications);
            string filename = ModificationFile(result);

            fileSystem.EnsureFolderExists(filename);
            fileSystem.Save(filename, writer.ToString());

            return(true);
        }
예제 #15
0
        public string Serialize(object value)
        {
            XmlWriterSettings settings = new XmlWriterSettings
            {
                NewLineHandling = NewLineHandling.None,
                Indent          = false
            };

            Utf8StringWriter stringWriter  = new Utf8StringWriter();
            XmlWriter        writer        = XmlWriter.Create(stringWriter, settings);
            XmlSerializer    xmlSerializer = new XmlSerializer(value.GetType());

            xmlSerializer.Serialize(writer, value);
            return(stringWriter.ToString());
        }
예제 #16
0
파일: Core.cs 프로젝트: Yelrah/FestlPlaner
 public static string ToIndentedString(XmlDocument doc)
 {
     if (doc == null)
     {
         return(string.Empty);
     }
     using (var utf8Writer = new Utf8StringWriter())
         using (var xmlTextWriter = new XmlTextWriter(utf8Writer))
         {
             xmlTextWriter.Formatting = Formatting.Indented;
             doc.Save(xmlTextWriter);
             xmlTextWriter.Close();
             return(utf8Writer.ToString());
         }
 }
예제 #17
0
        public static string ToXml <T>(this T obj) where T : class
        {
            var serializer = new DataContractSerializer(typeof(T));

            using (var sw = new Utf8StringWriter())
            {
                using (var writer = new XmlTextWriter(sw))
                {
                    writer.Formatting = Formatting.Indented; // indent the Xml so it's human readable
                    serializer.WriteObject(writer, obj);
                    writer.Flush();
                    return(sw.ToString());
                }
            }
        }
예제 #18
0
        private static string OnGeneratedCSProject(string path, string contents)
        {
#if STYLECOP_DEBUG
            Debug.Log("*.csproj change detected. Ensuring it adds StyleCop to project.");
#endif
            XDocument xml = XDocument.Parse(contents);

            AddStyleCopRoslynAnalyzerToProjectFile(xml);

            using (var str = new Utf8StringWriter())
            {
                xml.Save(str);
                return(str.ToString());
            }
        }
예제 #19
0
        public string SerializeObject(Text text)
        {
            if (text == null)
            {
                return(null);
            }

            var xmlSerializer = new XmlSerializer(typeof(Text));

            using (var stringWriter = new Utf8StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, text);
                return(stringWriter.ToString());
            }
        }
예제 #20
0
        private static async Task <string> Serialize(XmlSchema xmlSchema)
        {
            string actualXml;

            await using (var sw = new Utf8StringWriter())
                await using (var xw = XmlWriter.Create(sw, new XmlWriterSettings {
                    Indent = true, Async = true
                }))
                {
                    xmlSchema.Write(xw);
                    actualXml = sw.ToString();
                }

            return(actualXml);
        }
예제 #21
0
        public static string ToXmlStringMinified(object data)
        {
            var serializer = new XmlSerializer(data.GetType());



            using (var writer = new Utf8StringWriter())
                using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings {
                    Indent = false, OmitXmlDeclaration = true
                }))
                {
                    serializer.Serialize(xmlWriter, data);
                    return(writer.ToString());
                }
        }
예제 #22
0
        public string ToXmlString()
        {
            var ns = new XmlSerializerNamespaces();

            ns.Add(string.Empty, "http://www.linn.co.uk/2012/tickets");
            var serializer = new XmlSerializer(typeof(TicketRequestResource));
            var writer     = new Utf8StringWriter();

            serializer.Serialize(writer, this, ns);

            string xmlDataString = writer.ToString();

            xmlDataString = xmlDataString.Replace("\0", ""); // debug - remove any null terminators
            return(xmlDataString);
        }
예제 #23
0
        public static string SerializeToXml(this object obj)
        {
            var type = obj.GetType();

            string xml        = "";
            var    serializer = new XmlSerializer(type);

            using (StringWriter writer = new Utf8StringWriter())
            {
                serializer.Serialize(writer, obj);
                xml = writer.ToString();
            }

            return(xml.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n", ""));
        }
예제 #24
0
        internal static string Get(string companyToken, string transactionToken)
        {
            var xmlDocument = new XDocument(new XDeclaration("1.0", "utf-8", "no"),
                                            new XElement("API3G",
                                                         new XElement("CompanyToken", companyToken),
                                                         new XElement("Request", RequestTypes.ChargeTokenAuth),
                                                         new XElement("TransactionToken", transactionToken)
                                                         ));

            using (var sw = new Utf8StringWriter())
            {
                xmlDocument.Save(sw, SaveOptions.None);
                return(sw.ToString());
            }
        }
예제 #25
0
        public static StringContent ToStringContent(this object input, XmlSerializer serializer = null)
        {
            if (serializer == null)
            {
                serializer = new XmlSerializer(input.GetType());
            }

            using (var sw = new Utf8StringWriter())
            {
                serializer.Serialize(sw, input);
                var serializedString = sw.ToString();

                return(new StringContent(serializedString, Encoding.UTF8, "application/xml"));
            }
        }
예제 #26
0
        static ProjectFileHook()
        {
            ProjectFilesGenerator.ProjectFileGeneration += (string name, string content) =>
            {
                // parse the document and make some changes
                var document = XDocument.Parse(content);

                IncludeT4Template(document);

                // save the changes using the Utf8StringWriter
                var str = new Utf8StringWriter();
                document.Save(str);

                return(str.ToString());
            };
        }
예제 #27
0
        protected string Serialize(object obj)
        {
            XmlSerializer x   = new XmlSerializer(obj.GetType());
            var           xml = "";

            using (var sww = new Utf8StringWriter())
            {
                using (XmlWriter writer = XmlWriter.Create(sww))
                {
                    x.Serialize(writer, obj);
                    xml = sww.ToString(); // Your XML
                }
            }

            return(xml);
        }
예제 #28
0
        internal static string ToString <T>(T o) // where T : IComposedList<ISitemapEntity>
        {
            string result = string.Empty;

            if (o != null)
            {
                using (var stringWriter = new Utf8StringWriter())
                {
                    Type          type          = typeof(T);
                    XmlSerializer xmlSerialiser = new XmlSerializer(type);
                    xmlSerialiser.Serialize(stringWriter, o);
                    result = stringWriter.ToString();
                }
            }
            return(result);
        }
예제 #29
0
        public void reproduce_xml_enocoding_issue()
        {
            string xml = @"<some-element>© JNCC</some-element>";
            var doc = XDocument.Parse(xml);

            doc.Declaration = new XDeclaration("1.0", "utf-8", null);
            var writer = new Utf8StringWriter();
            doc.Save(writer, SaveOptions.None);
            string metaXmlDoc = writer.ToString();

            //
            //            string xml = @"<some-element>© JNCC</some-element>";
            //            var doc = XDocument.Parse(xml);
            //            doc.ToString().Should().Contain("©");
            //            doc.ToString().Should().NotContain("&copy;");
        }
예제 #30
0
        /// <summary>
        /// Converts to xml string and returns
        /// </summary>
        /// <returns></returns>
        public string Serialize <TPayload>(TPayload item)
        {
            var serializer   = new System.Xml.Serialization.XmlSerializer(typeof(TPayload));
            var stringWriter = new Utf8StringWriter();

            if (((IPayload)item).Xmlns.Count > 0)
            {
                serializer.Serialize(stringWriter, item, ((IPayload)item).Xmlns);
            }
            else
            {
                serializer.Serialize(stringWriter, item);
            }

            return(stringWriter.ToString());
        }
 public static string convertObjToXMLString(object obj)
 {
     try
     {
         XmlSerializer    serObj = new XmlSerializer(obj.GetType());
         Utf8StringWriter sw     = new Utf8StringWriter();
         XmlTextWriter    xtw    = new XmlTextWriter(sw);
         xtw.Formatting = Formatting.Indented;
         serObj.Serialize(xtw, obj);
         return(sw.ToString());
     }
     catch (Exception)
     {
         throw;
     }
 }
예제 #32
0
        public string Serialize(T toSerialize)
        {
            var xmlSerializer = new XmlSerializer(toSerialize.GetType());
            var settings      = new XmlWriterSettings
            {
                Indent             = true,
                OmitXmlDeclaration = false
            };

            using (var stream = new Utf8StringWriter())
                using (var writer = XmlWriter.Create(stream, settings))
                {
                    xmlSerializer.Serialize(writer, toSerialize, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
                    return(stream.ToString());
                }
        }
예제 #33
0
        private static string OnGeneration(string name, string content)
        {
            var document = XDocument.Parse(content);

            document.Root?.Descendants()
            .Where(c => c.Name.LocalName == "Reference")
            .Where(c => c.Attribute("Include")?.Value == "Boo.Lang")
            .Remove()
            ;

            var stream = new Utf8StringWriter();

            document.Save(stream);

            return(stream.ToString());
        }
예제 #34
0
        public void ToXMLDocumentTest()
        {
            string      source    = File.ReadAllText("onerecord.xml");
            FileMARCXML targetXML = new FileMARCXML(source);
            Record      target    = targetXML[0];

            string    expected = source;
            XDocument xdoc     = target.ToXMLDocument();

            using (StringWriter writer = new Utf8StringWriter())
            {
                xdoc.Save(writer);
                string actual = writer.ToString();
                Assert.AreEqual(expected, actual);
            }
        }
예제 #35
0
        public string ToStringWithDeclaration(XDocument doc)
        {
            if (doc == null)
            {
                throw new ArgumentNullException("doc");
            }
            StringWriter builder = new Utf8StringWriter();

            doc.Save(builder, SaveOptions.None);
            //StringBuilder builder = new StringBuilder();
            //using (TextWriter writer = new StringWriter(builder))
            //{
            //    doc.Save(writer);
            //}
            return(builder.ToString());
        }
예제 #36
0
        private async Task <ControlResponse> ProcessControlRequestInternalAsync(ControlRequest request)
        {
            var streamReader   = new StreamReader(request.InputXml, Encoding.UTF8);
            var readerSettings = new XmlReaderSettings
            {
                ValidationType  = ValidationType.None,
                CheckCharacters = false,
                IgnoreProcessingInstructions = true,
                IgnoreComments = true,
                Async          = true
            };

            using var reader = XmlReader.Create(streamReader, readerSettings);
            var requestInfo = await ParseRequestAsync(reader).ConfigureAwait(false);

            Logger.LogDebug("Received control request {Name}", requestInfo.LocalName);

            var settings = new XmlWriterSettings
            {
                Encoding        = Encoding.UTF8,
                CloseOutput     = false,
                CheckCharacters = false
            };

            var builder = new Utf8StringWriter();

            using var writer = XmlWriter.Create(builder, settings);
            writer.WriteStartDocument(true);
            writer.WriteStartElement("s", "Envelope", NsSoapEnv);
            writer.WriteAttributeString(string.Empty, "encodingStyle", NsSoapEnv, "http://schemas.xmlsoap.org/soap/encoding/");
            writer.WriteStartElement("s", "Body", NsSoapEnv);
            writer.WriteStartElement("u", requestInfo.LocalName + "Response", requestInfo.NamespaceUri);
            WriteResult(requestInfo.LocalName, requestInfo.Headers, writer);
            writer.WriteFullEndElement();
            writer.WriteFullEndElement();
            writer.WriteFullEndElement();
            writer.WriteEndDocument();
            writer.Flush();

            var xml = builder.ToString().Replace("xmlns:m=", "xmlns:u=", StringComparison.Ordinal);

            var controlResponse = new ControlResponse(xml);

            controlResponse.Headers.Add("EXT", string.Empty);

            return(controlResponse);
        }
        private static string SerializeRss(Rss rss)
        {
            var ns = new XmlSerializerNamespaces();

            foreach (var item in Rss.XmlNamespaces)
            {
                ns.Add(item.Key, item.Value);
            }

            var serializer = new XmlSerializer(rss.GetType());

            using (var writer = new Utf8StringWriter())
            {
                serializer.Serialize(writer, rss, ns);
                return(writer.ToString());
            }
        }
        public static XmlDocument ToXML(this Object oObject)
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            XmlSerializer xmlSerializer = new XmlSerializer(oObject.GetType());

            using (StringWriter writer = new Utf8StringWriter())
            {
                xmlSerializer.Serialize(writer, oObject, ns);
                var utf8 = writer.ToString();
                var XmlDoc = new XmlDocument();
                XmlDoc.LoadXml(utf8);

                return XmlDoc;
            }
        }
    // NOTE: Good to have
    // - automatic nuget package download
    // - stylecop file or directory exclude list

    static CodeAnalysisVsHook()
    {
        ProjectFilesGenerator.ProjectFileGeneration += (name, content) =>
        {
            var rulesetPath = GetRulesetFile();
            if (string.IsNullOrEmpty(rulesetPath))
                return content;

            var getStyleCopAnalyzersPath = GetStyleCopAnalyzersPath();
            if (string.IsNullOrEmpty(getStyleCopAnalyzersPath))
                return content;

            // Insert a ruleset file and StyleCop.Analyzers into a project file

            var document = XDocument.Parse(content);

            var ns = document.Root.Name.Namespace;

            var propertyGroup = document.Root.Descendants(ns + "PropertyGroup").FirstOrDefault();
            if (propertyGroup != null)
            {
                propertyGroup.Add(new XElement(ns + "CodeAnalysisRuleSet", rulesetPath));
            }

            var itemGroup = document.Root.Descendants(ns + "ItemGroup").LastOrDefault();
            if (itemGroup != null)
            {
                var newItemGroup = new XElement(ns + "ItemGroup");
                foreach (var file in Directory.GetFiles(getStyleCopAnalyzersPath + @"\analyzers\dotnet\cs", "*.dll"))
                {
                    newItemGroup.Add(new XElement(ns + "Analyzer", new XAttribute("Include", file)));
                }
                itemGroup.AddAfterSelf(newItemGroup);
            }

            var str = new Utf8StringWriter();
            document.Save(str);
            return str.ToString();
        };
    }
예제 #40
0
        /// <summary>
        /// Returns the dgml representation of the graph
        /// </summary>
        /// <returns>Graph as dgml string</returns>
        public string ToDgml()
        {
            XmlRootAttribute root = new XmlRootAttribute("DirectedGraph")
            {
                Namespace = "http://schemas.microsoft.com/vs/2009/dgml",
            };

            XmlSerializer serializer = new XmlSerializer(typeof(Graph), root);
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Indent = true,
                Encoding = Encoding.UTF8,
            };

            StringWriter dgml = new Utf8StringWriter();
            using (XmlWriter xmlWriter = XmlWriter.Create(dgml, settings))
            {
                serializer.Serialize(xmlWriter, this);
            }

            return dgml.ToString();
        }
예제 #41
0
    public string SerializeCommonData(){
 	using( StringWriter textWriter = new Utf8StringWriter() )
 	    {
 		var serializer = new XmlSerializer(typeof( CommonData ));
 		serializer.Serialize(textWriter, data);
 		return textWriter.ToString();
 	    }
    }
예제 #42
0
        /// <summary>
        /// Exports given AttributeSets, Entities and Templates to an XML and returns the XML as string.
        /// </summary>
        /// <param name="AttributeSetIDs"></param>
        /// <param name="EntityIDs"></param>
        /// <param name="TemplateIDs"></param>
        /// <param name="Messages"></param>
        /// <returns></returns>
        public string GenerateNiceXml()
        {
            var Doc = ExportXDocument;

            // Will be used to show an export protocoll in future
            Messages = null;

            // Write XDocument to string and return it
            var xmlSettings = new XmlWriterSettings();
            xmlSettings.Encoding = Encoding.UTF8;
            xmlSettings.ConformanceLevel = ConformanceLevel.Document;
            xmlSettings.Indent = true;

            using (var stringWriter = new Utf8StringWriter())
            {
                using (var writer = XmlWriter.Create(stringWriter, xmlSettings))
                    Doc.Save(writer);
                return stringWriter.ToString();
            }
        }
        /// <summary>
        /// Serializes an object as xml.
        /// </summary>
        /// <param name="objToSerialize">The object to serialize.</param>
        /// <returns>The serialized xml string.</returns>
        /// <remarks><paramref name="objToSerialize"/> must me XmlSerializable.
        /// </remarks>
        public static string SerializeAsXmlText(object objToSerialize)
        {
            string retval = "";

              using (StringWriter writer = new Utf8StringWriter()) {
            new XmlSerializer(objToSerialize.GetType()).Serialize(writer, objToSerialize);
            retval = writer.ToString();
              }
              return retval;
        }
예제 #44
0
      /// <summary>Formats the input BPL object into the output XML document.</summary>
      public override bool Format(BplObject input) {
         if (!PrepareFormatter(input)) return false;

         try {
            OutputXml = new XDocument {
               Declaration = new XDeclaration("1.0", "UTF-8", "yes")
            };
            _serializeObject(OutputXml, Input, null);
            NSMapping.Write(OutputXml.Root);
         } catch (Exception e) {
            AddException(e);
         }

         if (Success) {
            try {
               using (var strWriter = new Utf8StringWriter(CultureInfo.InvariantCulture)) {
                  using (var xmlWriter = XmlWriter.Create(strWriter, _getWriterSettings())) {
                     OutputXml.Save(xmlWriter);
                  }
                  Output = strWriter.ToString();
               }
            } catch (Exception e) {
               AddException(e);
            }
         }

         if (!Success) {
            Output = null;
            OutputXml = null;
         }

         return Success;
      }