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()); } }
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; }
/// <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(); }
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(); } }
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(); } }
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); }
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()); } }
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); }
/// <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); } }
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()); }; }
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); } }
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()); } }
/// <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); }
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()); }
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()); } }
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()); } } }
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()); } }
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()); } }
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); }
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()); } }
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); }
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", "")); }
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()); } }
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")); } }
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()); }; }
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); }
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); }
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("©"); }
/// <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; } }
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()); } }
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()); }
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); } }
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()); }
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(); }; }
/// <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(); }
public string SerializeCommonData(){ using( StringWriter textWriter = new Utf8StringWriter() ) { var serializer = new XmlSerializer(typeof( CommonData )); serializer.Serialize(textWriter, data); return textWriter.ToString(); } }
/// <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; }
/// <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; }