public void UpdateHeartbeat() { // Create or Update External XML For Last Update Check DateTime if (!File.Exists(CheckUpdateFile)) { DateTime DateTimeNow = DateTime.Now; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.Indent = true; XmlWriter writer = XmlWriter.Create(CheckUpdateFile, wSettings); writer.WriteStartDocument(); writer.WriteComment("This file is generated by WWIV5TelnetServer - DO NOT MODIFY."); writer.WriteStartElement("WWIV5UpdateStamp"); writer.WriteStartElement("LastChecked"); writer.WriteElementString("DateTime", DateTimeNow.ToString()); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); writer.Close(); } // Do Update Check updateTimer = new System.Timers.Timer(1000 * 60 * 60); // Hourly - Release Code //updateTimer = new System.Timers.Timer(1000 * 10); // 10 Seconds for Testing Only updateTimer.Elapsed += new ElapsedEventHandler(DoUpdateCheck); updateTimer.AutoReset = true; updateTimer.Enabled = true; if (Properties.Settings.Default.checkUpdates == "On Startup") { DoUpdateCheck(null, null); } }
internal WrappedSerializer(Serialization.DataFormat dataFormat, string streamName, TextWriter output) : base(dataFormat, streamName) { this.firstCall = true; this.textWriter = output; Serialization.DataFormat dataFormat1 = this.format; switch (dataFormat1) { case Serialization.DataFormat.Text: { return; } case Serialization.DataFormat.XML: { XmlWriterSettings xmlWriterSetting = new XmlWriterSettings(); xmlWriterSetting.CheckCharacters = false; xmlWriterSetting.OmitXmlDeclaration = true; this.xmlWriter = XmlWriter.Create(this.textWriter, xmlWriterSetting); this.xmlSerializer = new Serializer(this.xmlWriter); return; } default: { return; } } }
/// <summary> /// Serializes the specified <see cref="Element"/> to XML. /// </summary> /// <param name="root"> /// The <c>Element</c> to serialize, including all its children. /// </param> /// <remarks> /// The generated XML will be indented and have a full XML /// declaration header. /// </remarks> /// <exception cref="ArgumentNullException">root is null.</exception> public void Serialize(Element root) { var settings = new XmlWriterSettings(); settings.Indent = true; //settings.NamespaceHandling = NamespaceHandling.OmitDuplicates; this.Serialize(root, settings); }
private void write(string filePath) { try { XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = true; settings.CheckCharacters = true; settings.ConformanceLevel = ConformanceLevel.Document; settings.Encoding = Encoding.UTF8; settings.Indent = true; settings.IndentChars = "\t"; settings.NewLineChars = "\r\n"; using (XmlWriter writer = XmlWriter.Create(filePath, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("Config"); writer.WriteStartElement("FrequencyRange"); writer.WriteAttributeString("min", _minFreq.ToString()); writer.WriteAttributeString("max", _maxFreq.ToString()); writer.WriteEndElement(); writer.WriteElementString("DeviceID", _deviceId); writer.WriteEndElement(); writer.WriteEndDocument(); } } catch (Exception ex) { Logger.Instance.Log(LogType.Error, "設定ファイルの書き込みに失敗: " + ex.Message + "\r\n" + ex.StackTrace); } }
public void CreateDefinitions(WizardConfiguration wizardConfiguration) { var projectCollection = new XElement(Ns + "ProjectCollection"); var doc = new XDocument( new XElement(Ns + "VSTemplate", new XAttribute("Version", "3.0.0"), new XAttribute("Type", "ProjectGroup"), new XElement(Ns + "TemplateData", new XElement(Ns + "Name", wizardConfiguration.Name), new XElement(Ns + "Description", wizardConfiguration.Description), new XElement(Ns + "ProjectType", wizardConfiguration.ProjectType), new XElement(Ns + "DefaultName", wizardConfiguration.DefaultName), new XElement(Ns + "SortOrder", wizardConfiguration.SortOrder), new XElement(Ns + "Icon", wizardConfiguration.IconName)), new XElement(Ns + "TemplateContent", projectCollection), MakeWizardExtension( "LogoFX.Tools.Templates.Wizard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", $"LogoFX.Tools.Templates.Wizard.SolutionWizard") )); XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true }; var definitionFile = GetDefinitionFileName(); using (XmlWriter xw = XmlWriter.Create(definitionFile, settings)) { doc.Save(xw); } }
private static byte[] prepareRAWPayload(string location, string temperature, string weatherType) { MemoryStream stream = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8 }; XmlWriter writer = XmlTextWriter.Create(stream, settings); writer.WriteStartDocument(); writer.WriteStartElement("WeatherUpdate"); writer.WriteStartElement("Location"); writer.WriteValue(location); writer.WriteEndElement(); writer.WriteStartElement("Temperature"); writer.WriteValue(temperature); writer.WriteEndElement(); writer.WriteStartElement("WeatherType"); writer.WriteValue(weatherType); writer.WriteEndElement(); writer.WriteStartElement("LastUpdated"); writer.WriteValue(DateTime.Now.ToString()); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); byte[] payload = stream.ToArray(); return payload; }
/// <summary> /// Executes the request message on the target system and returns a response message. /// If there isn’t a response, this method should return null /// </summary> public Message Execute(Message message, TimeSpan timeout) { if (message.Headers.Action != "Submit") throw new ApplicationException("Unexpected Message Action"); //Parse the request message to extract the string and get out the body to send to the socket XmlDictionaryReader rdr = message.GetReaderAtBodyContents(); rdr.Read(); string input = rdr.ReadElementContentAsString(); //Interact with the socket this.Connection.Client.SendData(input); string output = this.Connection.Client.ReceiveData(); Debug.WriteLine(output); //Produce the response message StringBuilder outputString = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; XmlWriter replywriter = XmlWriter.Create(outputString, settings); replywriter.WriteStartElement("SendResponse", "http://acme.wcf.lob.paymentapplication/"); replywriter.WriteStartElement("SendResult"); replywriter.WriteString(Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(output))); replywriter.WriteEndElement(); replywriter.WriteEndElement(); replywriter.Close(); XmlReader replyReader = XmlReader.Create(new StringReader(outputString.ToString())); Message response = Message.CreateMessage(MessageVersion.Default, "Submit/Response", replyReader); return response; }
static string FormatText(string text) { XmlTextWriter writer = null; XmlDocument doc = new XmlDocument(); XmlWriterSettings xwSettings = new XmlWriterSettings(); string formattedText = string.Empty; try { doc.LoadXml(text); writer = new XmlTextWriter(".data.xml", null); writer.Formatting = Formatting.Indented; doc.Save(writer); writer.Close(); using (StreamReader sr = new StreamReader(".data.xml")) { formattedText = sr.ReadToEnd(); } } finally { File.Delete(".data.xml"); } return formattedText; }
private static void FixNuSpec(ProjectVersion version, string file) { XNamespace ns = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"; var readerSettings = new XmlReaderSettings { IgnoreComments = false, IgnoreWhitespace = false }; XDocument doc; using (var reader = XmlReader.Create(file, readerSettings)) { doc = XDocument.Load(reader); } var versionElement = doc.Descendants(ns + "version").Single(); versionElement.Value = version.FullText; var dependency = doc.Descendants(ns + "dependency").Where(x => (string)x.Attribute("id") == "NodaTime").FirstOrDefault(); if (dependency != null) { dependency.SetAttributeValue("version", version.Dependency); } var writerSettings = new XmlWriterSettings { Encoding = new UTF8Encoding(false), Indent = false, NewLineHandling = NewLineHandling.None, }; using (var writer = XmlWriter.Create(file, writerSettings)) { doc.Save(writer); } }
// This might better be rewrite to "examine two settings and return the existing one or new one if required". internal void MergeFrom (XmlWriterSettings other) { CloseOutput |= other.CloseOutput; OmitXmlDeclaration |= other.OmitXmlDeclaration; if (ConformanceLevel == ConformanceLevel.Auto) ConformanceLevel = other.ConformanceLevel; }
// 1. save XFA form XML stream to a file to inspect form fields public void SaveDatasetsXml(string readerPath) { using (var reader = new PdfReader(readerPath)) { var xfa = new XfaForm(reader); XmlDocument doc = xfa.DomDocument; //// remove namespace so XML is easier to read //if (!string.IsNullOrEmpty(doc.DocumentElement.NamespaceURI)) //{ // doc.DocumentElement.SetAttribute("xmlns", ""); // var temp = new XmlDocument(); // temp.LoadXml(doc.OuterXml); // doc = temp; //} var sb = new StringBuilder(); var xSettings = new XmlWriterSettings() { Indent = true, WriteEndDocumentOnClose = true }; using (var writer = XmlWriter.Create(sb, xSettings)) { doc.Save(writer); } File.WriteAllText(GetXmlPath(readerPath), sb.ToString()); } }
public override string Unformat(string value) { if (string.IsNullOrWhiteSpace(value)) return null; try { var stringBuilder = new StringBuilder(); var element = XElement.Parse(value); var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false, NewLineOnAttributes = false }; using (var xmlWriter = XmlWriter.Create(stringBuilder, settings)) { element.Save(xmlWriter); } return stringBuilder.ToString(); } catch (Exception ex) { Log.Error($"Error while unformatting expected XML field {value}. The raw value will be used instead.", ex, this); return value; } }
private string GenerateRequestXml(RequestInput input) { var sw = new StringWriter(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineOnAttributes = false; settings.OmitXmlDeclaration = true; using (XmlWriter writer = XmlWriter.Create(sw, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("GenerateRequest"); writer.WriteElementString("pxPayUserId", pxPayUserId); writer.WriteElementString("pxPayKey", pxPayKey); PropertyInfo[] properties = input.GetType().GetProperties(); foreach (PropertyInfo prop in properties) { if (prop.CanWrite) { string val = (string)prop.GetValue(input, null); if (val != null || val != string.Empty) { writer.WriteElementString(prop.Name, val); } } } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); } return sw.ToString(); }
string DotNetNuke.Entities.Modules.IPortable.ExportModule(int ModuleID) { StringBuilder strXML = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; XmlWriter Writer = XmlWriter.Create(strXML, settings); ArrayList alCategories = GetCategories(PortalId, true, -3); if (alCategories.Count > 0) { Writer.WriteStartElement("Categories"); foreach (CategoryInfo categoryInfo in alCategories) { Writer.WriteStartElement("Category"); Writer.WriteElementString("CategoryID", categoryInfo.CategoryID.ToString()); Writer.WriteElementString("Name", categoryInfo.CategoryName); Writer.WriteElementString("Description", categoryInfo.CategoryDescription); Writer.WriteElementString("Message", categoryInfo.Message); Writer.WriteElementString("Archived", categoryInfo.Archived.ToString()); Writer.WriteElementString("OrderID", categoryInfo.OrderID.ToString()); Writer.WriteElementString("ParentCategoryID", categoryInfo.ParentCategoryID.ToString()); Writer.WriteEndElement(); } Writer.WriteEndElement(); Writer.Close(); } else { return String.Empty; } return strXML.ToString(); }
public void Compile() { ParsedPath resxPath = Target.InputPaths.Where(f => f.Extension == ".resx").First(); ParsedPath stringsPath = Target.OutputPaths.Where(f => f.Extension == ".strings").First(); List<ResourceItem> resources = ReadResources(resxPath); XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.Indent = true; xmlSettings.IndentChars = "\t"; using (XmlWriter xmlWriter = XmlWriter.Create(stringsPath, xmlSettings)) { xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("Strings"); foreach (ResourceItem resource in resources) { if (resource.DataType == typeof(string)) { string value = resource.ValueString; xmlWriter.WriteStartElement("String"); xmlWriter.WriteAttributeString("Name", resource.Name); xmlWriter.WriteString(value); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } }
public static void SaveCustomers(List<Customer> customers) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = (" "); XmlWriter xmlOut = XmlWriter.Create(CustomerDB.path, settings); xmlOut.WriteStartDocument(); xmlOut.WriteStartElement("Customers"); foreach (Customer customer in customers) { switch (customer.GetType().Name) { case "Customer": Write((Customer)customer, xmlOut); break; case "RetailCustomer": WriteRetail((RetailCustomer)customer, xmlOut); break; case "WholesaleCustomer": WriteWholesale((WholesaleCustomer)customer, xmlOut); break; default: break; } } xmlOut.WriteEndElement(); xmlOut.Close(); }
/// <summary> /// Serializes current NumFunctionBoolType111 object into an XML string /// </summary> /// <returns>string XML value</returns> public virtual string Serialize(System.Text.Encoding encoding) { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings(); xmlWriterSettings.Encoding = encoding; xmlWriterSettings.Indent = true; xmlWriterSettings.IndentChars = " "; System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings); Serializer.Serialize(xmlWriter, this); memoryStream.Seek(0, SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream, encoding); return(streamReader.ReadToEnd()); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } }
/// <summary> /// Serialize ViewType object /// </summary> /// <returns>XML value</returns> public virtual string Serialize() { StreamReader streamReader = null; MemoryStream memoryStream = null; try { memoryStream = new MemoryStream(); System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings(); System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings); SerializerXML.Serialize(xmlWriter, this); memoryStream.Seek(0, SeekOrigin.Begin); streamReader = new StreamReader(memoryStream); return(streamReader.ReadToEnd()); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } }
public override string ToString() { var settings = new XmlWriterSettings { Indent = false, Encoding = new UTF8Encoding(false), NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true, NewLineOnAttributes = false, DoNotEscapeUriAttributes = true }; var sb = new StringBuilder(); using (var xw = XmlWriter.Create(sb, settings)) { xw.WriteStartElement("Role", Xmlnamespace); xw.WriteAttributeString("xmlns", "xsi", null, Xsinamespace); xw.WriteAttributeString("xsi", "type", Xsinamespace, Type); xw.WriteAttributeString("code", Code); xw.WriteAttributeString("codeSystem", CodeSystem); xw.WriteAttributeString("codeSystemName", CodeSystemName); xw.WriteAttributeString("displayName", DisplayName); xw.WriteEndElement(); xw.Flush(); return sb.ToString(); } }
public static void SaveEvents() { string fileName = Path.Combine(Settings.Instance.DataPath, Settings.Instance.Server + string.Format("{0}Events.xml", Path.DirectorySeparatorChar)); FileUtils.CreateDirIfNotExists(fileName); XmlWriterSettings xws = new XmlWriterSettings(); xws.Indent = true; xws.NewLineOnAttributes = true; lock (eventFileLock) lock (eventListLock) { using (XmlWriter writer = XmlWriter.Create(fileName, xws)) { writer.WriteStartDocument(); writer.WriteStartElement("Events"); foreach (EventStruct eventStruct in EventList) { writer.WriteStartElement("Event"); writer.WriteElementString("EventName", eventStruct.EventName); writer.WriteElementString("EventDate", eventStruct.EventDate.ToString(CultureInfo.InvariantCulture.DateTimeFormat)); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); } } }
public void WriteTo(object entity, IHttpEntity response, string[] codecParameters) { if (entity == null) return; bool isError = (response.Errors.Count > 0); string status = isError ? "error" : "ok"; var writerSettings = new XmlWriterSettings { OmitXmlDeclaration = true, Encoding = Encoding.UTF8, NamespaceHandling = NamespaceHandling.OmitDuplicates }; using (var xmlTextWriter = XmlWriter.Create(response.Stream, writerSettings)) { xmlTextWriter.WriteStartDocument(); xmlTextWriter.WriteStartElement("response"); xmlTextWriter.WriteAttributeString("xsi", "noNamespaceSchemaLocation", "", "http://api.7digital.com/1.2/static/7digitalAPI.xsd"); xmlTextWriter.WriteAttributeString("status", status); xmlTextWriter.WriteAttributeString("version", "1.2"); xmlTextWriter.WriteAttributeString("xmlns", "xsd", "", "http://www.w3.org/2001/XMLSchema"); xmlTextWriter.WriteAttributeString("xmlns", "xsi", "", "http://www.w3.org/2001/XMLSchema-instance"); if (!isError) OutputEntity(entity, xmlTextWriter); else OutputError(response, xmlTextWriter); xmlTextWriter.WriteEndElement(); } }
/// <summary> /// Đăng nhập vào hệ thống /// </summary> /// <param name="tenDangNhap"></param> /// <param name="matKhau"></param> /// <returns></returns> public static async Task<bool> login(string tenDangNhap, string matKhau, bool isRemember) { try { matKhau = Utilities.EncryptMD5(matKhau); var result = await SystemInfo.DatabaseModel.login(tenDangNhap, matKhau); if (!result) { SystemInfo.IsDangNhap = false; SystemInfo.MaNguoiDung = -1; SystemInfo.TenDangNhap = null; SystemInfo.MatKhauDangNhap = null; } else { SystemInfo.IsDangNhap = true; NguoiDung nguoiDung = await SystemInfo.DatabaseModel.getNguoiDungTenDangNhap(tenDangNhap); SystemInfo.MaNguoiDung = nguoiDung.MaNguoiDung; SystemInfo.TenDangNhap = tenDangNhap; SystemInfo.MatKhauDangNhap = matKhau; if (!(await SystemInfo.DatabaseModel.insertNguoiDungLocal(nguoiDung.MaNguoiDung, nguoiDung.HoTen, nguoiDung.NgaySinh, nguoiDung.Email, nguoiDung.SoDienThoai))) { await SystemInfo.DatabaseModel.updateNguoiDung(nguoiDung.MaNguoiDung, nguoiDung.HoTen, nguoiDung.NgaySinh, nguoiDung.SoDienThoai); } if (isRemember) { StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("AppConfig.qltcconfig"); using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { System.IO.Stream s = writeStream.AsStreamForWrite(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Async = true; settings.Indent = true; settings.CheckCharacters = false; using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(s, settings)) { XDocument xdoc = new XDocument(); XElement element = new XElement("ThongTinDangNhap"); element.Add(new XElement("MaNguoiDung", nguoiDung.MaNguoiDung + "")); element.Add(new XElement("TenDangNhap", tenDangNhap)); xdoc.Add(element); writer.Flush(); xdoc.Save(writer); } } } } return result; } catch (Exception ex) { throw ex; } }
private static FeedData GetFeed(SyndicationFeed feed, string contentType, WriteTo writeTo) { var feedData = new FeedData { ContentType = contentType }; if (feed.Items.Any()) { SyndicationItem item = (from syndicationItem in feed.Items orderby syndicationItem.PublishDate descending select syndicationItem).First(); feedData.LastModifiedDate = item.PublishDate.DateTime; } else { feedData.LastModifiedDate = DateTime.MinValue; } var xmlWriterSettings = new XmlWriterSettings { Encoding = new UTF8Encoding(false) }; var memoryStream = new MemoryStream(); using (XmlWriter writer = XmlWriter.Create(memoryStream, xmlWriterSettings)) { writeTo(writer); } memoryStream.Position = 0; var sr = new StreamReader(memoryStream); feedData.Content = sr.ReadToEnd(); feedData.ETag = feedData.Content.GetHashCode().ToString(); //} return feedData; }
/// <summary> /// 将指定对象的指定属性列表序列化为xml文本。 /// </summary> /// <param name="obj"></param> /// <param name="ps"></param> /// <returns></returns> public static string ToXmlText(object obj, IEnumerable<PropertyInfo> ps) { var sb = new StringBuilder(); var settings = new XmlWriterSettings { OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment, Indent = true, CloseOutput = false }; var writer = XmlWriter.Create(sb, settings); foreach (var p in ps) { writer.WriteStartElement(p.Name); //字符串返回CDATA节点 if (p.PropertyType == typeof (string)) { writer.WriteCData(Convert.ToString(p.GetValue(obj, null))); } else if (p.PropertyType == typeof (MessageType)) { writer.WriteCData(MessageTypeAttribute.ObtainMessageType((MessageType) p.GetValue(obj, null))); } else { writer.WriteValue(p.GetValue(obj, null)); } writer.WriteEndElement(); } writer.Flush(); writer.Close(); return sb.ToString(); }
/// <summary> /// Saves the settings to the provider. /// </summary> /// <param name="settings"> /// The settings. /// </param> public override void SaveSettings(StringDictionary settings) { if (settings == null) { throw new ArgumentNullException("settings"); } var filename = string.Format("{0}settings.xml", this.Folder); var writerSettings = new XmlWriterSettings { Indent = true }; // ------------------------------------------------------------ // Create XML writer against file path // ------------------------------------------------------------ using (var writer = XmlWriter.Create(filename, writerSettings)) { writer.WriteStartElement("settings"); foreach (string key in settings.Keys) { writer.WriteElementString(key, settings[key]); } writer.WriteEndElement(); } }
public XmlReader generateXml() { MemoryStream stream = new MemoryStream(); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.OmitXmlDeclaration = true; writerSettings.Indent = true; XmlWriter classWriter = XmlWriter.Create(stream, writerSettings); classWriter.WriteStartElement("class"); classWriter.WriteElementString("className", this.getClassName().Replace(".", "_")); classWriter.WriteElementString("controllerAlias", (this.getAliasName() != null) ? this.getAliasName() : "Not Set"); SortedList<string, MethodModel> methodsInClass = this.getUserSelectedMethodsInThisClass(); classWriter.WriteStartElement("methods"); foreach (KeyValuePair<string, MethodModel> methodPair in methodsInClass) { MethodModel methodAtHand = methodPair.Value; classWriter.WriteNode(methodAtHand.generateXml(), false); } classWriter.WriteEndElement(); classWriter.WriteEndElement(); classWriter.Flush(); stream.Position = 0; stream.Position = 0; XmlReader xmlReader = XmlReader.Create(stream); classWriter.Close(); return xmlReader; }
public IsoTextMessageEncoder(IsoTextMessageEncoderFactory factory) { _factory = factory; _writerSettings = new XmlWriterSettings {Encoding = Encoding.GetEncoding(factory.CharSet)}; _contentType = string.Format("{0}; charset={1}", _factory.MediaType, _writerSettings.Encoding.HeaderName); }
public static void Main(string[] args) { StringWriter stringWriter = new StringWriter(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings); string soapNamespace = "http://schemas.xmlsoap.org/soap/envelope/"; string bmlNamespace = "http://www.mincheol.com/bml"; xmlWriter.WriteStartElement("soap", "Envelope", soapNamespace); xmlWriter.WriteStartElement("Body", soapNamespace); xmlWriter.WriteStartElement("booklist", bmlNamespace); xmlWriter.WriteStartElement("book", bmlNamespace); xmlWriter.WriteStartElement("title", bmlNamespace); xmlWriter.WriteString(".NET �����ڸ� ���� XML Programming"); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.Close(); Console.WriteLine(stringWriter.ToString()); }
/// <summary> /// Serializes current TCPCommands object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize(System.Text.Encoding encoding) { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings(); xmlWriterSettings.Encoding = encoding; System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings); Serializer.Serialize(xmlWriter, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } }
public static void SaveRecentExperimentListToXML(RecentExperimentList pList, string pFilepath) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.CloseOutput = true; settings.CheckCharacters = true; // Create file using (System.Xml.XmlWriter writer = XmlWriter.Create(pFilepath, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("RecentExperiments"); foreach (var item in pList) { writer.WriteStartElement("RecentExperimentItem"); writer.WriteAttributeString("FullPath", item.FullPath); //writer.WriteAttributeString("Filename", item.Filename); writer.WriteAttributeString("LastAccessTime", item.LastAccessTime.ToString()); writer.WriteEndElement(); // RecentExperimentItem } writer.WriteEndElement(); // RecentExperiments writer.WriteEndDocument(); writer.Close(); } }
public static void SaveSales(List<Sale> sales) { // create the XmlWriterSettings object XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = (" "); // create the XmlWriter object XmlWriter xmlOut = XmlWriter.Create(Path, settings); // write the start of the document xmlOut.WriteStartDocument(); xmlOut.WriteStartElement("Sales"); // write each sale object to the xml file foreach (Sale sale in sales) { xmlOut.WriteStartElement("Sale"); xmlOut.WriteElementString("Code", sale.Code); xmlOut.WriteElementString("Description", sale.Description); xmlOut.WriteElementString("Price", Convert.ToString(sale.Price)); xmlOut.WriteEndElement(); } // write the end tag for the root element xmlOut.WriteEndElement(); // close the xmlWriter object xmlOut.Close(); }
/// <summary> /// Constructor /// </summary> public XmlDataContractSerializer() { XmlWriterSettings = new System.Xml.XmlWriterSettings { Encoding = _defaultEncoding, }; }
public static string Beautify(System.Xml.XmlDocument doc) { string strRetValue = null; System.Text.Encoding enc = System.Text.Encoding.UTF8; // enc = new System.Text.UTF8Encoding(false); System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings(); xmlWriterSettings.Encoding = enc; xmlWriterSettings.Indent = true; xmlWriterSettings.IndentChars = " "; xmlWriterSettings.NewLineChars = "\r\n"; xmlWriterSettings.NewLineOnAttributes = true; xmlWriterSettings.NewLineHandling = System.Xml.NewLineHandling.Replace; //xmlWriterSettings.OmitXmlDeclaration = true; xmlWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Document; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(ms, xmlWriterSettings)) { doc.Save(writer); writer.Flush(); ms.Flush(); writer.Close(); } // End Using writer ms.Position = 0; using (System.IO.StreamReader sr = new System.IO.StreamReader(ms, enc)) { // Extract the text from the StreamReader. strRetValue = sr.ReadToEnd(); sr.Close(); } // End Using sr ms.Close(); } // End Using ms /* * System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Always yields UTF-16, no matter the set encoding * using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings)) * { * doc.Save(writer); * writer.Close(); * } // End Using writer * strRetValue = sb.ToString(); * sb.Length = 0; * sb = null; */ xmlWriterSettings = null; return(strRetValue); } // End Function Beautify
protected virtual System.Xml.XmlWriterSettings _GetWriterSettings() { System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.Encoding = Encoding.UTF8; xmlWriterSettings.NewLineOnAttributes = true; xmlWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Document; return(xmlWriterSettings); }
private void SerializeToClipboard(ParticlePrefab prefab) { #if WINDOWS if (prefab == null) { return; } System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { Indent = true, OmitXmlDeclaration = true, NewLineOnAttributes = true }; XElement originalElement = null; foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.Particles)) { XDocument doc = XMLExtensions.TryLoadXml(configFile.Path); if (doc == null) { continue; } var prefabList = GameMain.ParticleManager.GetPrefabList(); foreach (ParticlePrefab otherPrefab in prefabList) { foreach (XElement subElement in doc.Root.Elements()) { if (!subElement.Name.ToString().Equals(prefab.Name, StringComparison.OrdinalIgnoreCase)) { continue; } SerializableProperty.SerializeProperties(prefab, subElement, true); originalElement = subElement; break; } } } if (originalElement == null) { originalElement = new XElement(prefab.Name); SerializableProperty.SerializeProperties(prefab, originalElement, true); } StringBuilder sb = new StringBuilder(); using (var writer = System.Xml.XmlWriter.Create(sb, settings)) { originalElement.WriteTo(writer); writer.Flush(); } Clipboard.SetText(sb.ToString()); #endif }
static private bool SaveObjectToFile <T>(T classContent, string appFile) { //remove from changecache when file not on disk during save if (!File.Exists(appFile)) { ChangeCache.Instance.RemoveFromCache(appFile, "file"); } //skip serializing if object hasn't changed if (!ChangeCache.Instance.ObjectHasChanged <T>(appFile, "file", classContent)) { return(true); } //create any missing folder string appFolder = Path.GetDirectoryName(appFile); Encoding enc = new UTF8Encoding(false); if (!Directory.Exists(appFolder)) { CreateFolderAndACL(appFolder); } if (!Directory.Exists(appFolder)) { throw new Exception(String.Format("Unable to create folder '{0}'", appFolder)); } //Serialize to XML and save default class content XmlSerializerNamespaces noNS = new XmlSerializerNamespaces(); noNS.Add("", ""); using (MemoryStream memStream = new MemoryStream()) { XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings() { // If set to true XmlWriter would close MemoryStream automatically and using would then do double dispose // Code analysis does not understand that. That's why there is a suppress message. CloseOutput = false, Encoding = enc, OmitXmlDeclaration = false, Indent = true }; using (XmlWriter xmlWrite = XmlWriter.Create(memStream, xmlWriterSettings)) { XmlSerializer serializer = new XmlSerializer(typeof(T)); serializer.Serialize(xmlWrite, classContent, noNS); xmlWrite.Close(); } File.WriteAllBytes(appFile, memStream.ToArray()); memStream.Close(); } return(true); }
public NoNamespaceXmlTextWriter(System.Text.StringBuilder sb, System.Xml.XmlWriterSettings settings) : base(new System.IO.StringWriter(sb, CultureInfo.InvariantCulture)) { Formatting = (settings.Indent) ? System.Xml.Formatting.Indented : System.Xml.Formatting.None; IndentChar = settings.IndentChars[0]; Indentation = settings.IndentChars.Length; }
void DumpXml(XPathDocument json, string filename) { var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; using (var writer = System.Xml.XmlWriter.Create(filename, settings)) { json.CreateNavigator().WriteSubtree(writer); } }
public static System.Xml.XmlWriterSettings DefaultSettings() { System.Xml.XmlWriterSettings xs = new System.Xml.XmlWriterSettings(); xs.OmitXmlDeclaration = false; xs.Encoding = System.Text.Encoding.UTF8; xs.Indent = true; xs.IndentChars = " "; return(xs); }
public void Export() { try { validate(); if (type == XMLExportType.Clients) { var settings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = false, Indent = true }; var ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer s = new XmlSerializer(typeof(Clients)); using (var writer = System.Xml.XmlWriter.Create(fileName, settings)) { s.Serialize(writer, cs, ns); } Populate_Control(); XmlSerializer s_Control = new XmlSerializer(typeof(Control)); using (var writer = System.Xml.XmlWriter.Create(fileNameControl, settings)) { s_Control.Serialize(writer, clientsControl, ns); } } else if (type == XMLExportType.Position) { var settings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = false, Indent = true }; var ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer s = new XmlSerializer(typeof(Positions)); using (var writer = System.Xml.XmlWriter.Create(fileName, settings)) { s.Serialize(writer, ps, ns); } Populate_Control(); XmlSerializer s_Control = new XmlSerializer(typeof(Control)); using (var writer = System.Xml.XmlWriter.Create(fileNameControl, settings)) { s_Control.Serialize(writer, positionControl, ns); } } } catch (Exception ex) { throw new Exception(ex.Message); }; }
public void Write_EDC(string save_file_path) { // ----------- Define xml header ------------- stringwriterUTF8 sw = new stringwriterUTF8(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.NewLineChars = "\r\n"; settings.Encoding = Encoding.UTF8; settings.IndentChars = " "; // next line indent 2 space settings.OmitXmlDeclaration = false; // write header xml version and encode XmlSerializerNamespaces names = new XmlSerializerNamespaces(); names.Add(string.Empty, string.Empty); System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sw, settings); XmlSerializer EDC_serialize = new XmlSerializer(this.GetType()); // typeof(EDC_Report)); EDC_serialize.Serialize(writer, this, names); writer.Close(); if (!Directory.Exists(Path.GetDirectoryName(save_file_path))) { Directory.CreateDirectory(Path.GetDirectoryName(save_file_path)); } try { string temp_name = save_file_path + ".tmp"; using (FileStream fs = System.IO.File.Open(temp_name, FileMode.Create)) { using (StreamWriter EDCWriter = new StreamWriter(fs, Encoding.UTF8)) { EDCWriter.Write(sw.ToString()); EDCWriter.Flush(); fs.Flush(); } } if (System.IO.File.Exists(save_file_path)) { System.IO.File.Delete(save_file_path); } while (System.IO.File.Exists(save_file_path)) { Thread.Sleep(1); } System.IO.File.Move(temp_name, save_file_path); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void btnSave_Click(object sender, EventArgs e) { string OptionFile = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\SmartWeb\SmartWebOption.xml"; try { //Directory가 존재 하지 않은 경우 Directory를 생성 한다. if (System.IO.Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\SmartWeb") == false) { System.IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\SmartWeb"); } System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(OptionFile, settings); writer.WriteStartElement("configuration"); writer.WriteStartElement("appSettings"); writer.WriteStartElement("add"); writer.WriteAttributeString("key", "Language"); writer.WriteAttributeString("value", Convert.ToString(cboLanguage.SelectedIndex + 1)); writer.WriteEndElement(); writer.WriteStartElement("add"); writer.WriteAttributeString("key", "AutoLogOutTime"); if (txtAutoLotoutTime.Text.Trim() == "") { writer.WriteAttributeString("value", "0"); } else { writer.WriteAttributeString("value", txtAutoLotoutTime.Text); } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.Flush(); writer.Close(); // 2020-01-31-김미경 : 언어 변경에 따른 메시지 출력. //CmnFunction.ShowMsgBox(RptMessages.GetMessage("STD035", GlobalVariable.gcLanguage)); } catch (Exception ex) { MessageBox.Show(ex.Message); } GlobalVariable.gcLanguage = Convert.ToChar(cboLanguage.SelectedIndex + 1); GlobalVariable.giLogOutTime = txtAutoLotoutTime.Text.Trim() == "" ? 0 : Convert.ToInt32(txtAutoLotoutTime.Text); this.Close(); }
// Writes Default Settings if not existing private static void SetSettings(DatabaseSettings defaultSettings) { var path = Environment.CurrentDirectory + "DatabaseSettings.xml"; var xmlSerializer = new DataContractSerializer(typeof(DatabaseSettings)); var settings = new System.Xml.XmlWriterSettings { Indent = true, NewLineOnAttributes = true }; var SettingsFile = XmlWriter.Create(path, settings); xmlSerializer.WriteObject(SettingsFile, settings); SettingsFile.Close(); }
// Use this for initialization void Start() { if (System.IO.File.Exists(configPath) == false) { Xml.XmlWriterSettings settings = new Xml.XmlWriterSettings(); settings.Indent = true; string levelsPath = "Assets/scenes/"; string[] loaderPath = System.IO.Directory.GetFiles(levelsPath); ConfigWriter cfgFile = ConfigWriter.Create(configPath, settings); cfgFile.WriteStartElement("Config"); cfgFile.WriteStartElement("Levels"); cfgFile.WriteAttributeString("LevelsPath", levelsPath.ToString()); foreach (string file in loaderPath) { if (file.EndsWith(".meta") == false) { cfgFile.WriteElementString("Map", file.Remove(0, levelsPath.Length).Remove(file.Length - (levelsPath.Length + 6)).ToString()); } } cfgFile.WriteEndElement(); cfgFile.WriteEndElement(); cfgFile.WriteEndDocument(); cfgFile.Flush(); cfgFile.Close(); } else { if (colorsDictionary.Count > 0) { return; } //load colors ConfigReader cfgFile = new ConfigReader(); cfgFile.Load(configPath); Xml.XmlNodeList colorNodes = cfgFile.GetElementsByTagName("Color"); foreach (Xml.XmlElement nodes in colorNodes) { colorsDictionary.Add(nodes.GetAttribute("colorName"), new string[] { nodes.GetAttribute("one"), nodes.GetAttribute("two"), nodes.GetAttribute("three"), nodes.GetAttribute("four") }); } } //Debug.Log ( "config says hello"); }
public static System.Xml.XmlWriter CreateWriter(string file) { var settings = new System.Xml.XmlWriterSettings { Indent = true, }; var writer = System.Xml.XmlWriter.Create(file, settings); writer.WriteStartDocument(); writer.WriteStartElement("Database"); return(writer); }
public void SaveAs(string fileName, Encoding encoding) { System.Xml.XmlWriterSettings setting = new System.Xml.XmlWriterSettings(); setting.Encoding = encoding; setting.Indent = true; setting.IndentChars = " "; setting.NewLineChars = "\r\n"; System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(fileName, setting); this.XmlDoc.WriteTo(writer); writer.Close(); }
public void HaloReachRebuildUnicTags() { BlamVersion game = BlamVersion.HaloReach_Xbox; CacheFileOutputInfoArgs.TestMethodSerial(TestContext, CacheRebuildUnicTagsMethod, game, kDirectoryXbox, @"Retail\maps\mainmenu.map"); CacheFileOutputInfoArgs.TestMethodSerial(TestContext, CacheRebuildUnicTagsMethod, game, kDirectoryXbox, @"Retail\dlc_noble\dlc_invasion.map"); string results_path = BuildResultPath(kTagDumpPath, game, "", "settings", "xml"); var xml_settings = new System.Xml.XmlWriterSettings(); xml_settings.Indent = true; xml_settings.IndentChars = " "; xml_settings.Encoding = System.Text.Encoding.ASCII; using (var s = System.Xml.XmlTextWriter.Create(results_path, xml_settings)) { s.WriteStartDocument(true); s.WriteStartElement("settingsDefinitions"); s.WriteAttributeString("game", game.ToString()); s.WriteStartElement("options"); foreach (var kv in Blam.HaloReach.Tags.text_value_pair_definition_group.SettingParameters) { s.WriteStartElement("entry"); s.WriteAttributeString("key", kv.Key.ToString()); s.WriteAttributeString("value", Path.GetFileName(kv.Value)); s.WriteAttributeString("tagName", kv.Value); s.WriteEndElement(); } s.WriteEndElement(); s.WriteStartElement("categories"); foreach (var kv in Blam.HaloReach.Tags.multiplayer_variant_settings_interface_definition_group.SettingCategories) { s.WriteStartElement("entry"); s.WriteAttributeString("key", kv.Key.ToString()); s.WriteAttributeString("value", Path.GetFileName(kv.Value.TagName)); s.WriteAttributeString("title", kv.Value.Title); s.WriteAttributeString("tagName", kv.Value.TagName); s.WriteEndElement(); } s.WriteEndElement(); s.WriteEndElement(); s.WriteEndDocument(); } }
public static int Grabar() { // grabar configuracion System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.IndentChars = (" "); string tmp = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase; // PDA string strAppDir = tmp.Substring(1, tmp.Length - 11); //le quito \\plugin.exe // PDA using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(strAppDir + "\\config.xml", settings)) //PDA { // Write XML data. writer.WriteStartElement("config"); System.Globalization.NumberFormatInfo nfi = new System.Globalization.CultureInfo("en-US", false).NumberFormat; if (latitud == 0) { writer.WriteElementString("lat", "0"); } else { writer.WriteElementString("lat", latitud.ToString("###.###########", nfi)); } if (longitud == 0) { writer.WriteElementString("lon", "0"); } else { writer.WriteElementString("lon", longitud.ToString("###.###########", nfi)); } writer.WriteElementString("tick", segundos.ToString()); writer.WriteElementString("tack", minutos.ToString()); writer.WriteElementString("gps", gps); writer.WriteElementString("auto", avisoauto.ToString()); writer.WriteElementString("map", avisomapa.ToString()); writer.WriteElementString("mapurl", avisomapaurl.ToString()); writer.WriteElementString("width", avisowidth.ToString()); writer.WriteElementString("height", avisoheight.ToString()); writer.WriteElementString("top", avisotop.ToString()); writer.WriteElementString("left", avisoleft.ToString()); writer.WriteElementString("port", port); writer.WriteElementString("speed", speed); writer.WriteElementString("user", usuario.ToString()); writer.WriteElementString("pass", clave.ToString()); writer.WriteElementString("lang", idioma.ToString()); writer.WriteElementString("song", sonido.ToString()); writer.WriteElementString("explorer", explorador.ToString()); writer.Flush(); } return(0); }
public void WriteToLog(String inLogMessage, MsgType msgtype) { _readWriteLock.EnterWriteLock(); try { LogFileName = DateTime.Now.ToString("dd-MM-yyyy"); if (!Directory.Exists(LogPath)) { Directory.CreateDirectory(LogPath); } var settings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = true, Indent = true }; StringBuilder sbuilder = new StringBuilder(); using (StringWriter sw = new StringWriter(sbuilder)) { using (XmlWriter w = XmlWriter.Create(sw, settings)) { w.WriteStartElement("LogInfo"); w.WriteElementString("Time", DateTime.Now.ToString()); if (msgtype == MsgType.Error) { w.WriteElementString("Error", inLogMessage); } else if (msgtype == MsgType.Info) { w.WriteElementString("Info", inLogMessage); } w.WriteEndElement(); } } using (StreamWriter Writer = new StreamWriter(LogFullPath, true, Encoding.UTF8)) { Writer.WriteLine(sbuilder.ToString()); } } catch (Exception ex) { } finally { _readWriteLock.ExitWriteLock(); } }
//'/primepractice/clinical/stylesheets/labresult.xsl 'Regular Result //'/primepractice/clinical/stylesheets/labdocument.xsl 'Microbiology //'/primepractice/clinical/stylesheets/document.xsl 'Transcription public static string TranslateLabResultXMLToMobileHTML(string sXML, string sStyleSheetType) { try { System.Xml.Xsl.XslCompiledTransform xsltTransform = new System.Xml.Xsl.XslCompiledTransform(); System.IO.StreamReader xsltStream; switch (sStyleSheetType.ToLower()) { case "document": xsltStream = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MobileDocument.xslt")); break; case "labdocument": xsltStream = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MobileLabDocument.xslt")); break; case "labresult": xsltStream = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MobileLabResult.xslt")); break; default: xsltStream = null; break; } System.Xml.XmlTextReader xtextreader = new System.Xml.XmlTextReader(xsltStream); xsltTransform.Load(xtextreader); System.Xml.XmlDocument xLabResultDom = new System.Xml.XmlDocument(); xLabResultDom.LoadXml(sXML); System.Xml.XmlWriterSettings xWriterSettings = new System.Xml.XmlWriterSettings(); xWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; StringBuilder sb = new StringBuilder(); //Dim xDoc As New System.Xml.XPath.XPathDocument(New System.IO.StringReader(sXML)) //'xsltTransform.Transform(xDoc, System.Xml.XmlWriter.Create(sb, xWriterSettings)) xsltTransform.Transform(new System.Xml.XmlNodeReader(xLabResultDom), System.Xml.XmlWriter.Create(sb, xWriterSettings)); return(sb.ToString()); } catch (Exception ex) { throw new Exception("Exception in Sirona.Utilities.Translator.TranslateLabResultXMLToMobileHTML: \n" + ex.Message); } }
public static void Object2XmlFile(object obj, string sFileName) { var x = new System.Xml.Serialization.XmlSerializer(obj.GetType()); var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); using (var fs = new System.IO.FileStream(sFileName, System.IO.FileMode.Create)) { var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; settings.Encoding = System.Text.Encoding.UTF8; var writer = System.Xml.XmlWriter.Create(fs, settings); x.Serialize(writer, obj, ns); } }
private void Save(Stream outputStream) { XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings() { CloseOutput = false, Encoding = new UTF8Encoding(false, true), OmitXmlDeclaration = false, Indent = true }; using (XmlWriter xmlWriter = XmlWriter.Create(outputStream, xmlWriterSettings)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(IntegrityList)); xmlSerializer.Serialize(xmlWriter, this); } }
public static string XmlEncode(string value) { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { ConformanceLevel = System.Xml.ConformanceLevel.Fragment }; StringBuilder builder = new StringBuilder(); using (var writer = System.Xml.XmlWriter.Create(builder, settings)) { writer.WriteString(value); } return(builder.ToString()); }
public static void Serialize(object o, Stream outputStream) { XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings() { CloseOutput = false, Encoding = new UTF8Encoding(false, true), OmitXmlDeclaration = false, Indent = true }; using (XmlWriter xmlWriter = XmlWriter.Create(outputStream, xmlWriterSettings)) { DataContractSerializer dataContractSerializer = new DataContractSerializer(o.GetType()); dataContractSerializer.WriteObject(xmlWriter, o); } }
public void SaveAsXmlToDisk(string filename) { var editor = ObjectFactory.GetInstance <ICanvas>( ); _properties.CameraPosition = editor.Camera.Position; XElement document = ToXml( ); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Encoding = new UTF8Encoding(false); //This byte mark encoding isn't handled nicely by some programs settings.Indent = true; //Keeping the previous indent using (XmlWriter writer = XmlTextWriter.Create(filename, settings)) { document.Save(writer); } }
public static string SerializeToString(this XmlSerializer s, object o, string ns) { var n = new XmlSerializerNamespaces(); n.Add("", ns); var builder = new System.Text.StringBuilder(); var settings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = true, Indent = true }; using (var writer = System.Xml.XmlWriter.Create(builder, settings)) { s.Serialize(writer, o, n); } return(builder.ToString()); }
public static string FormatXML(System.Xml.XmlDocument doc) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { Indent = true, IndentChars = "\t", NewLineChars = "\r\n", NewLineHandling = System.Xml.NewLineHandling.Replace }; settings.OmitXmlDeclaration = true; using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings)) { doc.Save(writer); } return(sb.ToString()); }
public static string Object2Xml(object obj) { string sXml = ""; var x = new System.Xml.Serialization.XmlSerializer(obj.GetType()); var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); using (var ms = new System.IO.MemoryStream()) { var settings = new System.Xml.XmlWriterSettings(); settings.Indent = false; settings.OmitXmlDeclaration = true; settings.Encoding = System.Text.Encoding.UTF8; var writer = System.Xml.XmlWriter.Create(ms, settings); x.Serialize(writer, obj, ns); sXml = System.Text.Encoding.UTF8.GetString(ms.GetBuffer()); } return(sXml); }
private void Serialize <T>(T obj, string sConfigFilePath) { try { System.Xml.Serialization.XmlSerializer XmlBuddy = new System.Xml.Serialization.XmlSerializer(typeof(T)); System.Xml.XmlWriterSettings MySettings = new System.Xml.XmlWriterSettings(); MySettings.Indent = true; MySettings.CloseOutput = true; MySettings.OmitXmlDeclaration = true; System.Xml.XmlWriter MyWriter = System.Xml.XmlWriter.Create(sConfigFilePath, MySettings); XmlBuddy.Serialize(MyWriter, obj); MyWriter.Flush(); MyWriter.Close(); } catch (Exception ex) { account.Log(new ErrorTextInformation(ex.Message + ex.StackTrace), 0); } }
public static string SerializeStandardObject <T>(T obj, XmlSerializerNamespaces ns, Encoding enc) { XmlSerializer serializer = new XmlSerializer(typeof(T), new Type[] { obj.GetType() }); using (MemoryStream ms = new MemoryStream()) { XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings() { CloseOutput = false, Encoding = enc }; using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(ms, xmlWriterSettings)) { serializer.Serialize(xw, obj, (ns ?? new XmlSerializerNamespaces())); } return(enc.GetString(ms.ToArray())); } }