public XmlRenderer(System.Windows.Size size) { Size = size; m_stream = new MemoryStream(); m_writer = new XmlTextWriter(m_stream, Encoding.UTF8); m_writer.Formatting = Formatting.Indented; }
/// <summary> /// Define o valor de uma configuração /// </summary> /// <param name="file">Caminho do arquivo (ex: c:\program.exe.config)</param> /// <param name="key">Nome da configuração</param> /// <param name="value">Valor a ser salvo</param> /// <returns></returns> public static bool SetValue(string file, string key, string value) { var fileDocument = new XmlDocument(); fileDocument.Load(file); var nodes = fileDocument.GetElementsByTagName(AddElementName); if (nodes.Count == 0) { return false; } for (var i = 0; i < nodes.Count; i++) { var node = nodes.Item(i); if (node == null || node.Attributes == null || node.Attributes.GetNamedItem(KeyPropertyName) == null) continue; if (node.Attributes.GetNamedItem(KeyPropertyName).Value == key) { node.Attributes.GetNamedItem(ValuePropertyName).Value = value; } } var writer = new XmlTextWriter(file, null) { Formatting = Formatting.Indented }; fileDocument.WriteTo(writer); writer.Flush(); writer.Close(); return true; }
private bool SaveRegister(string RegisterKey) { try { Encryption enc = new Encryption(); FileStream fs = new FileStream("reqlkd.dll", FileMode.Create); XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8); // Khởi động tài liệu. w.WriteStartDocument(); w.WriteStartElement("QLCV"); // Ghi một product. w.WriteStartElement("Register"); w.WriteAttributeString("GuiNumber", enc.EncryptData(sGuiID)); w.WriteAttributeString("Serialnumber", enc.EncryptData(sSerial)); w.WriteAttributeString("KeyRegister", enc.EncryptData(RegisterKey, sSerial + sGuiID)); w.WriteEndElement(); // Kết thúc tài liệu. w.WriteEndElement(); w.WriteEndDocument(); w.Flush(); w.Close(); fs.Close(); return true; } catch (Exception ex) { return false; } }
static void Main(string[] args) { string textFile = "../../PersonData.txt"; string xmlFile = "../../Person.xml"; using (XmlTextWriter xmlWriter = new XmlTextWriter(xmlFile, Encoding.GetEncoding("utf-8"))) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.IndentChar = '\t'; xmlWriter.Indentation = 1; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("person"); xmlWriter.WriteAttributeString("id", "1"); using (StreamReader fileReader = new StreamReader(textFile)) { string name = fileReader.ReadLine(); xmlWriter.WriteElementString("name", name); string address = fileReader.ReadLine(); xmlWriter.WriteElementString("address", address); string phone = fileReader.ReadLine(); xmlWriter.WriteElementString("phone", phone); } xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); } }
private static void WriteXMLDocument(List<List<Review>> allResults) { string fileName = "../../reviews-search-results.xml"; Encoding encoding = Encoding.GetEncoding("UTF-8"); using (XmlTextWriter writer = new XmlTextWriter(fileName, encoding)) { writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 1; writer.WriteStartDocument(); writer.WriteStartElement("search-results"); foreach (var results in allResults) { writer.WriteStartElement("result-set"); var orderedResult = (from e in results orderby e.DateOfCreation select e).ToList(); WriteBookInXML(orderedResult, writer); writer.WriteEndElement(); } writer.WriteEndDocument(); } }
public void updateCartFile(List<CartObject> newCartObj) { bool found = false; string cartFile = "C:\\Users\\Kiran\\Desktop\\cart.xml"; if (!File.Exists(cartFile)) { XmlTextWriter xWriter = new XmlTextWriter(cartFile, Encoding.UTF8); xWriter.Formatting = Formatting.Indented; xWriter.WriteStartElement("carts"); xWriter.WriteStartElement("cart"); xWriter.WriteAttributeString("emailId", Session["emailId"].ToString()); xWriter.Close(); } XmlDocument doc = new XmlDocument(); doc.Load(cartFile); foreach (CartObject cartItem in newCartObj) { foreach (XmlNode xNode in doc.SelectNodes("carts")) { XmlNode cartNode = xNode.SelectSingleNode("cart"); if (cartNode.Attributes["emailId"].InnerText == Session["emailId"].ToString()) { found = true; XmlNode bookNode = doc.CreateElement("book"); XmlNode nameNode = doc.CreateElement("name"); nameNode.InnerText = cartItem.itemName; XmlNode priceNode = doc.CreateElement("price"); priceNode.InnerText = cartItem.itemPrice.ToString(); XmlNode quantityNode = doc.CreateElement("quantity"); quantityNode.InnerText = "1"; bookNode.AppendChild(nameNode); bookNode.AppendChild(priceNode); bookNode.AppendChild(quantityNode); cartNode.AppendChild(bookNode); } } if(!found) { XmlNode cartNode = doc.CreateElement("cart"); cartNode.Attributes["emailId"].InnerText = Session["emailId"].ToString(); XmlNode bookNode = doc.CreateElement("book"); XmlNode nameNode = doc.CreateElement("name"); nameNode.InnerText = cartItem.itemName; XmlNode priceNode = doc.CreateElement("price"); priceNode.InnerText = cartItem.itemPrice.ToString(); XmlNode quantityNode = doc.CreateElement("quantity"); quantityNode.InnerText = "1"; bookNode.AppendChild(nameNode); bookNode.AppendChild(priceNode); bookNode.AppendChild(quantityNode); cartNode.AppendChild(bookNode); doc.DocumentElement.AppendChild(cartNode); } } doc.Save(cartFile); }
public static string Serialize(IEnumerable<MicroDataEntry> entries) { StringBuilder sb = new StringBuilder(3000); using (StringWriter sw = new StringWriter(sb)) { using (XmlTextWriter xw = new XmlTextWriter(sw)) { xw.WriteStartElement("microData"); foreach (MicroDataEntry microDataEntry in entries) { xw.WriteStartElement("entry"); if (microDataEntry.ContentType.HasValue) { xw.WriteAttributeString("contentType", microDataEntry.ContentType.Value.ToString()); } xw.WriteAttributeString("entryType", microDataEntry.Type.ToString()); xw.WriteAttributeString("selector", microDataEntry.Selector); xw.WriteAttributeString("value", microDataEntry.Value); xw.WriteEndElement(); } xw.WriteEndElement(); } } return sb.ToString(); }
private void CreateConfig() { this.ConfigFileLocation = Path.Combine(this.ThemeDirectory, "Theme.config"); using (var xml = new XmlTextWriter(this.ConfigFileLocation, Encoding.UTF8)) { xml.WriteStartDocument(true); xml.Formatting = Formatting.Indented; xml.Indentation = 4; xml.WriteStartElement("configuration"); xml.WriteStartElement("appSettings"); this.AddKey(xml, "ThemeName", this.Info.ThemeName); this.AddKey(xml, "Author", this.Info.Author); this.AddKey(xml, "AuthorUrl", this.Info.AuthorUrl); this.AddKey(xml, "AuthorEmail", this.Info.AuthorEmail); this.AddKey(xml, "ConvertedBy", this.Info.ConvertedBy); this.AddKey(xml, "ReleasedOn", this.Info.ReleasedOn); this.AddKey(xml, "Version", this.Info.Version); this.AddKey(xml, "Category", this.Info.Category); this.AddKey(xml, "Responsive", this.Info.Responsive ? "Yes" : "No"); this.AddKey(xml, "Framework", this.Info.Framework); this.AddKey(xml, "Tags", string.Join(",", this.Info.Tags)); this.AddKey(xml, "HomepageLayout", this.Info.HomepageLayout); this.AddKey(xml, "DefaultLayout", this.Info.DefaultLayout); xml.WriteEndElement(); //appSettings xml.WriteEndElement(); //configuration xml.Close(); } }
// XmlWriterSample1/form.cs private void button1_Click(object sender, System.EventArgs e) { // change to match you path structure string fileName="booknew.xml"; //create the XmlTextWriter XmlTextWriter tw=new XmlTextWriter(fileName,null); //set the formatting to indented tw.Formatting=Formatting.Indented; tw.WriteStartDocument(); //Start creating elements and attributes tw.WriteStartElement("book"); tw.WriteAttributeString("genre","Mystery"); tw.WriteAttributeString("publicationdate","2001"); tw.WriteAttributeString("ISBN","123456789"); tw.WriteElementString("title","Case of the Missing Cookie"); tw.WriteStartElement("author"); tw.WriteElementString("name","Cookie Monster"); tw.WriteEndElement(); tw.WriteElementString("price","9.99"); tw.WriteEndElement(); tw.WriteEndDocument(); //clean up tw.Flush(); tw.Close(); }
public static void Save(VProject vProject, XmlTextWriter xml) { Debug.Assert(vProject.ProjectDescriptor != null); Debug.Assert(vProject.ProjectDescriptor.Code != null); Debug.Assert(vProject.Items != null); xml.WriteStartElement("Code"); xml.WriteValue(vProject.ProjectDescriptor.Code); xml.WriteEndElement(); xml.WriteStartElement("ProjectItems"); foreach (var item in vProject.Items) { xml.WriteStartElement("ProjectItem"); xml.WriteStartElement("DisplayName"); xml.WriteValue(item.DisplayName); xml.WriteEndElement(); xml.WriteStartElement("Code"); xml.WriteValue(item.Descriptor.Code); xml.WriteEndElement(); xml.WriteEndElement(); } xml.WriteEndElement(); }
/// <summary> /// Renders the object as KML, and calls upon any children to do the same /// </summary> /// <param name="kml"></param> public override void ToKML(XmlTextWriter kml) { string coord = Longitude.ToString() + "," + Latitude.ToString(); if (!Altitude.Equals(Single.NaN)) coord += "," + Altitude.ToString(); kml.WriteElementString("coordinates", coord); }
public Object DeserializeObject(String pXmlizedString) { XmlSerializer xs = new XmlSerializer(typeof(EntryList)); MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); return xs.Deserialize(memoryStream); }
private void SetUpWriter() { sw = new StringWriter (); xtw = new XmlTextWriter (sw); xtw.QuoteChar = '\''; xtw.Formatting = Formatting.None; }
protected virtual void WriteChild(XmlTextWriter writer, ContentItem child) { using (ElementWriter childElement = new ElementWriter("child", writer)) { childElement.WriteAttribute("id", child.ID); } }
/// <summary>Renders the specified component name.</summary> /// <param name="output">The output.</param> /// <param name="componentName">Name of the component.</param> private void Render(XmlTextWriter output, string componentName) { var renderings = Context.Database.SelectItems("fast://*[@@templateid='{99F8905D-4A87-4EB8-9F8B-A9BEBFB3ADD6}']"); var matches = renderings.Where(r => string.Compare(r.Name, componentName, StringComparison.InvariantCultureIgnoreCase) == 0).ToList(); if (matches.Count == 0) { matches = renderings.Where(r => r.Name.IndexOf(componentName, StringComparison.InvariantCultureIgnoreCase) >= 0).ToList(); } if (matches.Count > 1) { output.WriteString(string.Format("Ambigeous match. {0} matches found.", matches.Count)); return; } if (matches.Count == 0) { output.WriteString("The component was not found."); return; } this.Render(output, matches.First()); }
private void AddKey(XmlTextWriter xml, string key, string value) { xml.WriteStartElement("add"); xml.WriteAttributeString("key", key); xml.WriteAttributeString("value", value); xml.WriteEndElement(); //add }
public static void Main() { using (XmlTextWriter writer = new XmlTextWriter(DirPath, Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.IndentChar = ' '; writer.Indentation = 2; string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); writer.WriteStartDocument(); writer.WriteStartElement("directories"); try { TraverseDirectory(desktopPath, writer); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("Change the desktopPath."); } writer.WriteEndDocument(); } Console.WriteLine("Xml document successfully created."); }
public static void Save( WorldSaveEventArgs e ) { if ( !Directory.Exists( "Saves/Accounts" ) ) Directory.CreateDirectory( "Saves/Accounts" ); string filePath = Path.Combine( "Saves/Accounts", "accounts.xml" ); using ( StreamWriter op = new StreamWriter( filePath ) ) { XmlTextWriter xml = new XmlTextWriter( op ); xml.Formatting = Formatting.Indented; xml.IndentChar = '\t'; xml.Indentation = 1; xml.WriteStartDocument( true ); xml.WriteStartElement( "accounts" ); xml.WriteAttributeString( "count", m_Accounts.Count.ToString() ); foreach ( Account a in GetAccounts() ) a.Save( xml ); xml.WriteEndElement(); xml.Close(); } }
private void InternalMergeFormChanges(XmlTextWriter xml) { if (xml == null) { throw new ArgumentNullException("xml"); } ReportDesignerWriter rpd = new ReportDesignerWriter(); XmlHelper.CreatePropperDocument(xml); foreach (IComponent component in viewContent.Host.Container.Components) { if (!(component is Control)) { rpd.Save(component,xml); } } xml.WriteEndElement(); xml.WriteStartElement("SectionCollection"); // we look only for Sections foreach (IComponent component in viewContent.Host.Container.Components) { BaseSection b = component as BaseSection; if (b != null) { rpd.Save(component,xml); } } //SectionCollection xml.WriteEndElement(); //Reportmodel xml.WriteEndElement(); xml.WriteEndDocument(); xml.Close(); }
/// <summary> /// Serializes this AccountTag instance to an XmlTextWriter. /// </summary> /// <param name="xml">The XmlTextWriter instance from which to serialize.</param> public void Save(XmlTextWriter xml) { xml.WriteStartElement("tag"); xml.WriteAttributeString("name", m_Name); xml.WriteString(m_Value); xml.WriteEndElement(); }
protected virtual void WriteRole(XmlTextWriter writer, AuthorizedRole ar) { using (ElementWriter role = new ElementWriter("role", writer)) { role.Write(ar.Role); } }
public void DecodeArrayAllowsEmptyRootElementAsLongAsXmlWriterIsStarted() { StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); writer.WriteStartElement("root"); JsonMLCodec.Decode(new JsonTextReader(new StringReader("[]")), writer); }
public void Save(XmlTextWriter writer) { writer.WriteStartElement("PauseScreen"); if (ChangeSound != null) ChangeSound.Save(writer); if (PauseSound != null) PauseSound.Save(writer); if (Background != null) writer.WriteElementString("Background", Background.Relative); foreach (PauseWeaponInfo weapon in weapons) weapon.Save(writer); if (LivesPosition != Point.Empty) { writer.WriteStartElement("Lives"); writer.WriteAttributeString("x", LivesPosition.X.ToString()); writer.WriteAttributeString("y", LivesPosition.Y.ToString()); writer.WriteEndElement(); } foreach (var item in inventory) { item.Save(writer); } writer.WriteEndElement(); }
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) { return Task.Factory.StartNew(() => { XmlWriter writer = new XmlTextWriter(writeStream, new UTF8Encoding(false)); bool summary = requestMessage.RequestSummary(); if (type == typeof(OperationOutcome)) { Resource resource = (Resource)value; FhirSerializer.SerializeResource(resource, writer, summary); } else if (type.IsAssignableFrom(typeof(Resource))) { Resource resource = (Resource)value; FhirSerializer.SerializeResource(resource, writer, summary); content.Headers.ContentLocation = resource.ExtractKey().ToUri(); } else if (type == typeof(FhirResponse)) { FhirResponse response = (value as FhirResponse); if (response.HasBody) FhirSerializer.SerializeResource(response.Resource, writer, summary); } writer.Flush(); }); }
/// <summary>Serialize the <c>XmlRpcResponse</c> to the output stream.</summary> /// <param name="output">An <c>XmlTextWriter</c> stream to write data to.</param> /// <param name="obj">An <c>Object</c> to serialize.</param> /// <seealso cref="XmlRpcResponse"/> public override void Serialize(XmlTextWriter output, Object obj) { XmlRpcResponse response = (XmlRpcResponse) obj; output.WriteStartDocument(); output.WriteStartElement(METHOD_RESPONSE); if (response.IsFault) output.WriteStartElement(FAULT); else { output.WriteStartElement(PARAMS); output.WriteStartElement(PARAM); } output.WriteStartElement(VALUE); SerializeObject(output,response.Value); output.WriteEndElement(); output.WriteEndElement(); if (!response.IsFault) output.WriteEndElement(); output.WriteEndElement(); }
static int Main(string[] args) { Console.WriteLine("XMLTo v0.1 [www.mosa-project.org]"); Console.WriteLine("Copyright 2009 by the MOSA Project. Licensed under the New BSD License."); Console.WriteLine("Written by Philipp Garcia ([email protected])"); Console.WriteLine(); Console.WriteLine("Usage: XMLTo <xml file> <xsl file> <output file>"); Console.WriteLine(); if (args.Length < 3) { Console.Error.WriteLine("ERROR: Missing arguments"); return -1; } try { XPathDocument myXPathDoc = new XPathDocument(args[0]); XslCompiledTransform myXslTrans = new XslCompiledTransform(); myXslTrans.Load(args[1]); XmlTextWriter myWriter = new XmlTextWriter(args[2], null); myXslTrans.Transform(myXPathDoc, null, myWriter); return 0; } catch (Exception e) { Console.Error.WriteLine("Exception: {0}", e.ToString()); return -1; } }
public override bool Execute() { try { var document = new XmlDocument(); document.Load(this.XmlFileName); var navigator = document.CreateNavigator(); var nsResolver = new XmlNamespaceManager(navigator.NameTable); if (!string.IsNullOrEmpty(this.Prefix) && !string.IsNullOrEmpty(this.Namespace)) { nsResolver.AddNamespace(this.Prefix, this.Namespace); } var expr = XPathExpression.Compile(this.XPath, nsResolver); var iterator = navigator.Select(expr); while (iterator.MoveNext()) { iterator.Current.DeleteSelf(); } using (var writer = new XmlTextWriter(this.XmlFileName, Encoding.UTF8)) { writer.Formatting = Formatting.Indented; document.Save(writer); writer.Close(); } } catch (Exception exception) { base.Log.LogErrorFromException(exception); return false; } base.Log.LogMessage("Updated file '{0}'", new object[] { this.XmlFileName }); return true; }
/// <summary> /// Creates an instance of the given type from the specified Internet resource. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An <see cref="XsltArgumentList"/> containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="type">The requested type.</param> /// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param> /// <returns>An newly created instance.</returns> public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type, string xmlPath) { StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); if (xsltUrl == null) { LoadHtmlAsXml(htmlUrl, writer); } else { if (xmlPath == null) { LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer); } else { LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, xmlPath); } } writer.Flush(); StringReader sr = new StringReader(sw.ToString()); XmlTextReader reader = new XmlTextReader(sr); XmlSerializer serializer = new XmlSerializer(type); object o; try { o = serializer.Deserialize(reader); } catch (InvalidOperationException ex) { throw new Exception(ex + ", --- xml:" + sw); } return o; }
private static void ProcessSearchQueries(XmlTextWriter writer) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("..\\..\\performance-test.xml"); foreach (XmlNode query in xmlDoc.SelectNodes("review-queries/query")) { SaveQueryToLog(query.OuterXml); var type = query.Attributes.GetNamedItem("type"); switch (type.Value) { case "by-period": // Start date and end date are mandatory. DateTime startDate = DateTime.Parse(query.GetChildText("start-date")); DateTime endDate = DateTime.Parse(query.GetChildText("end-date")); var reviewsByPeriod = BookstoreDAL.FindReviewsByPeriod(startDate, endDate); WriteReviews(writer, reviewsByPeriod); break; case "by-author": string authorName = query.GetChildText("author-name"); var reviewsByAuthor = BookstoreDAL.FindReviewsByAuthor(authorName); WriteReviews(writer, reviewsByAuthor); break; default: throw new ArgumentException("Type not supported!"); } } }
public ActionResult Index() { var doc = new XDocument(new XDeclaration("1.0", "utf-8", null)); var indexElement = new XElement(SitemapXmlNamespace + "sitemapindex"); foreach (var sitemapData in _sitemapRepository.GetAllSitemapData()) { var sitemapElement = new XElement( SitemapXmlNamespace + "sitemap", new XElement(SitemapXmlNamespace + "loc", _sitemapRepository.GetSitemapUrl(sitemapData)) ); indexElement.Add(sitemapElement); } doc.Add(indexElement); Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress); Response.AppendHeader("Content-Encoding", "gzip"); byte[] sitemapIndexData; using (var ms = new MemoryStream()) { var xtw = new XmlTextWriter(ms, Encoding.UTF8); doc.Save(xtw); xtw.Flush(); sitemapIndexData = ms.ToArray(); } return new FileContentResult(sitemapIndexData, "text/xml"); }
public virtual void SaveToXml(System.Xml.XmlTextWriter xmlWriter) { xmlWriter.WriteStartElement("Layer"); xmlWriter.WriteAttributeString("Id", ID.ToString()); xmlWriter.WriteAttributeString("Type", this.GetType().FullName); xmlWriter.WriteAttributeString("Name", Name); xmlWriter.WriteAttributeString("ReferenceFrame", referenceFrame); xmlWriter.WriteAttributeString("Color", SavedColor.Save(color)); xmlWriter.WriteAttributeString("Opacity", opacity.ToString()); xmlWriter.WriteAttributeString("StartTime", StartTime.ToString()); xmlWriter.WriteAttributeString("EndTime", EndTime.ToString()); xmlWriter.WriteAttributeString("FadeSpan", FadeSpan.ToString()); xmlWriter.WriteAttributeString("FadeType", FadeType.ToString()); this.WriteLayerProperties(xmlWriter); xmlWriter.WriteEndElement(); }
// Form activated methods private bool transformBasicXML(String inputFilename, String outputFilename, String xslLocation) { System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform(); xslt.Load(xslLocation); //Create a new XPathDocument and load the XML data to be transformed. System.Xml.XPath.XPathDocument mydata = new System.Xml.XPath.XPathDocument(inputFilename); //Create an XmlTextWriter which outputs to the console. System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(outputFilename, System.Text.Encoding.UTF8); //Transform the data and send the output to the file. xslt.Transform(mydata, null, writer); writer.Close(); return(true); }
// <Snippet1> private void WriteSchemaWithXmlTextWriter(DataSet thisDataSet) { // Set the file path and name. Modify this for your purposes. string filename = "SchemaDoc.xml"; // Create a FileStream object with the file path and name. System.IO.FileStream stream = new System.IO.FileStream (filename, System.IO.FileMode.Create); // Create a new XmlTextWriter object with the FileStream. System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.Unicode); // Write the schema into the DataSet and close the reader. thisDataSet.WriteXmlSchema(writer); writer.Close(); }
/// <summary> /// Serializes the object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="inObject">The input object.</param> /// <returns></returns> public static string SerializeObject <T>(T inObject, Encoding encodeType) { if (encodeType == null) { encodeType = Encoding.UTF8; } // create a MemoryStream here, we are just working exclusively in memory using (Stream stream = new System.IO.MemoryStream()) { // The XmlTextWriter takes a stream and encoding as one of its constructors using (XmlTextWriter xtWriter = new System.Xml.XmlTextWriter(stream, encodeType)) { try { XmlSerializer serializer = new XmlSerializer(typeof(T)); serializer.Serialize(xtWriter, inObject); xtWriter.Flush(); // go back to the beginning of the Stream to read its contents stream.Seek(0, System.IO.SeekOrigin.Begin); // read back the contents of the stream and supply the encoding using (StreamReader reader = new System.IO.StreamReader(stream, encodeType)) { string result = reader.ReadToEnd(); return(result); } } catch (Exception e) { return(e.Message); } finally { if (stream != null) { stream.Close(); } if (xtWriter != null) { xtWriter.Close(); } } } } }
/// <summary> /// 获取xml字符串 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xmlRootName"></param> /// <param name="t"></param> /// <returns></returns> public static string ObjectToXmlString <T>(string xmlRootName, T t) where T : class { string str = ""; try { if (t == null) { return(string.Empty); } if (string.IsNullOrEmpty(xmlRootName)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); using (MemoryStream memoryStream = new System.IO.MemoryStream()) { using (XmlTextWriter xtw = new System.Xml.XmlTextWriter(memoryStream, Encoding.UTF8)) { XmlSerializerNamespaces xns = new XmlSerializerNamespaces(); xns.Add("", ""); xmlSerializer.Serialize(xtw, t, xns); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); using (System.IO.StreamReader streamReader = new System.IO.StreamReader(memoryStream, Encoding.UTF8)) { return(streamReader.ReadToEnd()); } } } } else { using (var writer = new StringWriter()) { var xs = new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName)); xs.Serialize(writer, t); str = writer.ToString(); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(str); }
/// <summary> /// creates logfile /// </summary> private void open() { if (this.opened_) { return; } try { if (theSwitch.Level > TraceLevel.Off) { xmlwriter = new System.Xml.XmlTextWriter(this.file_path, null); xmlwriter.Formatting = System.Xml.Formatting.Indented; xmlwriter.WriteStartDocument(); //Write the ProcessingInstruction node. string PItext = theSwitch.style_instruction_pitext(string.Empty); if (PItext != string.Empty) { xmlwriter.WriteProcessingInstruction("xml-stylesheet", PItext); } xmlwriter.WriteStartElement("trace"); xmlwriter.WriteAttributeString("timestamp", timestamp()); xmlwriter.WriteAttributeString("assembly", this.asm.FullName); xmlwriter.WriteStartElement("switch"); // xmlwriter.WriteAttributeString( "displayname" , theSwitch.DisplayName) ; // xmlwriter.WriteAttributeString( "description" , theSwitch.Description ) ; xmlwriter.WriteAttributeString("level", theSwitch.Level.ToString()); xmlwriter.WriteEndElement(); // close 'switch' } this.opened_ = true; } catch (Exception x) { evlog.internal_log.error(x); x = null; } finally { if (this.xmlwriter != null) { xmlwriter.Close(); } this.xmlwriter = null; } }
public void WriteDirectoryXMLFile(string folder, string fnaam) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); GlobalDataStore.Logger.Debug("Updating " + fnaam + " ..."); List <LabelX.Toolbox.LabelXItem> items = new List <LabelX.Toolbox.LabelXItem>(); DirectoryInfo FolderDirectoryInfo = new DirectoryInfo(folder); LabelX.Toolbox.Toolbox.GetFilesFromFolderTree(FolderDirectoryInfo.FullName, ref items); //items = alle ingelezen bestanden. Nu gaan wegschrijven. System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement root = doc.CreateElement("LabelXItems"); foreach (LabelX.Toolbox.LabelXItem item in items) { if (getFileExt(item.Name) == ".xml") { continue; } System.Xml.XmlElement itemXML = doc.CreateElement("item"); itemXML.SetAttribute("name", item.Name); itemXML.SetAttribute("hash", item.Hash); root.AppendChild(itemXML); } doc.AppendChild(root); MemoryStream ms = new MemoryStream(); System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8) { Formatting = System.Xml.Formatting.Indented }; doc.WriteContentTo(tw); doc.Save(folder + fnaam); tw.Close(); sw.Stop(); GlobalDataStore.Logger.Debug("Creating the XML Hash file for the directory took: " + sw.ElapsedMilliseconds + " ms (" + folder + ")"); sw.Reset(); }
/// <summary> /// 将对象序列化为指定编码格式的文本。 /// </summary> /// <param name="obj">要序列化为文本的对象。</param> /// <param name="encoding">文本编码格式。如果为空引用则默认为UTF-8编码格式。</param> /// <param name="extraTypes">要序列化的其他对象类型的 Type 数组。</param> /// <returns>如果 /// <paramref name="obj"/>是空引用,返回 <seealso cref="String.Empty"/>, 反之返回序列化文本。</returns> public override string ToSerializedString(T obj, Encoding encoding) { string ret = string.Empty; //XmlSerializer serializer = new XmlSerializer(typeof(T)); MemoryStream ms = null; XmlTextWriter xtw = null; StreamReader sr = null; try { ms = new MemoryStream(); xtw = new System.Xml.XmlTextWriter(ms, encoding); //xtw.Formatting = System.Xml.Formatting.Indented; serializer.Serialize(xtw, obj); ms.Seek(0, SeekOrigin.Begin); sr = new StreamReader(ms); ret = sr.ReadToEnd(); } catch (Exception ex) { Logger.Error(ex.ToString()); throw ex; } finally { if (xtw != null) { xtw.Close(); xtw = null; } if (sr != null) { sr.Dispose(); sr = null; } if (ms != null) { ms.Dispose(); ms = null; } } return(ret); }
public void Save(System.Xml.XmlTextWriter tw, string localName) { tw.WriteStartElement(localName); tw.WriteAttributeString("Version", "1"); tw.WriteElementString("DirectionRecentFirst", System.Xml.XmlConvert.ToString(_viewDirectionRecentIsFirst)); tw.WriteStartElement("ColumnWidths"); var colWidths = null != _view ? _view.ColumnWidths : new double[0]; tw.WriteAttributeString("Count", XmlConvert.ToString(colWidths.Length)); for (int i = 0; i < colWidths.Length; i++) { tw.WriteElementString("Width", XmlConvert.ToString(colWidths[i])); } tw.WriteEndElement(); // "ColumnWidths" tw.WriteEndElement(); // localName }
public static string IdentXML(string xml) { string result = ""; MemoryStream mStream = new MemoryStream(); System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(mStream, Encoding.Unicode); System.Xml.XmlDocument document = new System.Xml.XmlDocument(); try { // Load the XmlDocument with the XML. document.LoadXml(xml); writer.Formatting = System.Xml.Formatting.Indented; // Write the XML into a formatting XmlTextWriter document.WriteContentTo(writer); writer.Flush(); mStream.Flush(); // Have to rewind the MemoryStream in order to read // its contents. mStream.Position = 0; // Read MemoryStream contents into a StreamReader. StreamReader sReader = new StreamReader(mStream); // Extract the text from the StreamReader. string formattedXml = sReader.ReadToEnd(); result = formattedXml; } catch (System.Xml.XmlException) { // Handle the exception } mStream.Close(); writer.Close(); return(result); }
/// <summary> /// Serialises an object to XML. /// </summary> /// <param name="obj">The object to be serialised.</param> /// <param name="extraTypes">Any extra types needed in serialisation.</param> /// <returns>XML data.</returns> /// <exception cref="InvalidOperationException">Thrown if the serialisation fails.</exception> internal static byte[] ToXmlBytes(object obj, SysColl.ICollection <Type> extraTypes) { // Creating an XmlTextReader from the XML document using (var xmlStream = new System.IO.MemoryStream()) { using (var xmlWriter = new SXml.XmlTextWriter(xmlStream, System.Text.Encoding.UTF8)) { var extraTypesArr = new Type[extraTypes.Count]; extraTypes.CopyTo(extraTypesArr, 0); // Serialising var serializer = m_serialiserCache.GetSerializer(obj.GetType(), extraTypesArr); serializer.Serialize(xmlWriter, obj); // Returning a byte array return(xmlStream.ToArray()); } } }
/// <summary> /// 序列化成xml字符串。用法:List《MyObject》 lMy = new List《MyObject》(); lMy.Add(ceshi); lMy.Add(ceshi2); string s = Serialize(lMy); /// </summary> /// <param name="obj"></param> /// <returns>序列化后的字符串</returns> public static string Serialize(object obj, Type type) { XmlSerializer xs = new XmlSerializer(type); using (MemoryStream ms = new MemoryStream()) { System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, System.Text.Encoding.UTF8); xtw.Formatting = System.Xml.Formatting.Indented; xs.Serialize(xtw, obj); ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms)) { string str = sr.ReadToEnd(); xtw.Close(); ms.Close(); return(str); } } }
private void WriteDataSetToXmlFile(DataSet ds, string filename) { if (DropDownList1.SelectedItem.Text == "MYSQL") { string absoluteFileName = Server.MapPath("~/MYSQL/" + filename); System.IO.FileStream myFileStream = new System.IO.FileStream(absoluteFileName, System.IO.FileMode.Create); System.Xml.XmlTextWriter myXmlWriter = new System.Xml.XmlTextWriter(myFileStream, System.Text.Encoding.Unicode); ds.WriteXml(myXmlWriter); myXmlWriter.Close(); } else { string absoluteFileName = Server.MapPath("~/SQLSERVER/" + filename); System.IO.FileStream myFileStream = new System.IO.FileStream(absoluteFileName, System.IO.FileMode.Create); System.Xml.XmlTextWriter myXmlWriter = new System.Xml.XmlTextWriter(myFileStream, System.Text.Encoding.Unicode); ds.WriteXml(myXmlWriter); myXmlWriter.Close(); } }
private object GenerateXmlFromObject(string propName, object value) { object result = null; if (value is Type) { result = GenerateXmlFromTypeCore((Type)value); } //******************************** if (value.GetType().ToString().EndsWith("[]")) { System.IO.MemoryStream mem = new MemoryStream(); System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(mem, Encoding.UTF8); try { System.Xml.Serialization.XmlSerializer serial = new System.Xml.Serialization.XmlSerializer(value.GetType()); serial.Serialize(writer, value); writer.Close(); result = Encoding.UTF8.GetString(mem.ToArray()); mem.Dispose(); } catch (Exception) { } finally { writer.Close(); mem.Dispose(); } } //*************************************** if (result == null) { result = value.ToString(); } return(new XElement(propName, result)); }
public override void WriteLayerProperties(System.Xml.XmlTextWriter xmlWriter) { xmlWriter.WriteAttributeString("TimeSeries", TimeSeries.ToString()); xmlWriter.WriteAttributeString("BeginRange", BeginRange.ToString()); xmlWriter.WriteAttributeString("EndRange", EndRange.ToString()); xmlWriter.WriteAttributeString("Decay", Decay.ToString()); xmlWriter.WriteAttributeString("CoordinatesType", CoordinatesType.ToString()); xmlWriter.WriteAttributeString("LatColumn", LatColumn.ToString()); xmlWriter.WriteAttributeString("LngColumn", LngColumn.ToString()); xmlWriter.WriteAttributeString("GeometryColumn", GeometryColumn.ToString()); xmlWriter.WriteAttributeString("AltType", AltType.ToString()); xmlWriter.WriteAttributeString("MarkerMix", MarkerMix.ToString()); xmlWriter.WriteAttributeString("ColorMap", ColorMap.ToString()); xmlWriter.WriteAttributeString("MarkerColumn", MarkerColumn.ToString()); xmlWriter.WriteAttributeString("ColorMapColumn", ColorMapColumn.ToString()); xmlWriter.WriteAttributeString("PlotType", PlotType.ToString()); xmlWriter.WriteAttributeString("MarkerIndex", MarkerIndex.ToString()); xmlWriter.WriteAttributeString("MarkerScale", MarkerScale.ToString()); xmlWriter.WriteAttributeString("AltUnit", AltUnit.ToString()); xmlWriter.WriteAttributeString("AltColumn", AltColumn.ToString()); xmlWriter.WriteAttributeString("StartDateColumn", StartDateColumn.ToString()); xmlWriter.WriteAttributeString("EndDateColumn", EndDateColumn.ToString()); xmlWriter.WriteAttributeString("SizeColumn", SizeColumn.ToString()); xmlWriter.WriteAttributeString("HyperlinkFormat", HyperlinkFormat.ToString()); xmlWriter.WriteAttributeString("HyperlinkColumn", HyperlinkColumn.ToString()); xmlWriter.WriteAttributeString("ScaleFactor", ScaleFactor.ToString()); xmlWriter.WriteAttributeString("PointScaleType", PointScaleType.ToString()); xmlWriter.WriteAttributeString("ShowFarSide", ShowFarSide.ToString()); xmlWriter.WriteAttributeString("RaUnits", RaUnits.ToString()); xmlWriter.WriteAttributeString("HoverTextColumn", NameColumn.ToString()); xmlWriter.WriteAttributeString("XAxisColumn", XAxisColumn.ToString()); xmlWriter.WriteAttributeString("XAxisReverse", XAxisReverse.ToString()); xmlWriter.WriteAttributeString("YAxisColumn", YAxisColumn.ToString()); xmlWriter.WriteAttributeString("YAxisReverse", YAxisReverse.ToString()); xmlWriter.WriteAttributeString("ZAxisColumn", ZAxisColumn.ToString()); xmlWriter.WriteAttributeString("ZAxisReverse", ZAxisReverse.ToString()); xmlWriter.WriteAttributeString("CartesianScale", CartesianScale.ToString()); xmlWriter.WriteAttributeString("CartesianCustomScale", CartesianCustomScale.ToString()); xmlWriter.WriteAttributeString("DynamicData", DynamicData.ToString()); xmlWriter.WriteAttributeString("AutoUpdate", AutoUpdate.ToString()); xmlWriter.WriteAttributeString("DataSourceUrl", DataSourceUrl.ToString()); }
public override void WriteLayerProperties(System.Xml.XmlTextWriter xmlWriter) { if (imageSet.WcsImage != null) { xmlWriter.WriteAttributeString("Extension", Path.GetExtension(imageSet.WcsImage.Filename)); } if (imageSet.WcsImage is FitsImage) { FitsImage fi = imageSet.WcsImage as FitsImage; xmlWriter.WriteAttributeString("ScaleType", fi.lastScale.ToString()); xmlWriter.WriteAttributeString("MinValue", fi.lastBitmapMin.ToString()); xmlWriter.WriteAttributeString("MaxValue", fi.lastBitmapMax.ToString()); } xmlWriter.WriteAttributeString("OverrideDefault", overrideDefaultLayer.ToString()); ImageSetHelper.SaveToXml(xmlWriter, imageSet, ""); base.WriteLayerProperties(xmlWriter); }
///<summary> /// SyggestSync is a goodies to ask a proper sync of what's /// present in RAM, and what's present in the XML file. ///</summary> public void SuggestSync() { XmlTextWriter writer = new System.Xml.XmlTextWriter("configuration.xml", null); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("entries"); foreach (string key in m_Matches.Keys) { writer.WriteStartElement("entry"); writer.WriteElementString("key", key); writer.WriteElementString("value", (string)m_Matches[key]); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); writer.Close(); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { thread_showSth(); txtMsg.Text = ""; xmlWriter = new XmlTextWriter(Server.MapPath("./1234.xml"), System.Text.Encoding.UTF8); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("队列"); xmlWriter.WriteStartElement("跳舞"); xmlWriter.WriteString("boy,girl"); xmlWriter.WriteEndElement(); //写文档结束,调用WriteEndDocument方法 xmlWriter.WriteEndDocument(); // 关闭textWriter xmlWriter.Close(); } }
public string ConvertProject(string xsltPath, string projectName) { var xTrf = new System.Xml.Xsl.XslCompiledTransform(true); var xTrfArg = new System.Xml.Xsl.XsltArgumentList(); var xSet = new System.Xml.Xsl.XsltSettings(true, true); var wSet = new System.Xml.XmlWriterSettings(); var mstr = new System.Xml.XmlTextWriter(new System.IO.MemoryStream(), System.Text.Encoding.UTF8); //var mstr = new System.Xml.XmlTextWriter(xsltPath + "test.xml", System.Text.Encoding.UTF8); var doc = new System.Xml.XmlDocument(); wSet = xTrf.OutputSettings; xTrf.Load(CopyXSLTFile(xsltPath), xSet, new XmlUrlResolver()); xTrfArg.AddParam("ProjectName", "", projectName); mstr.WriteStartDocument(); mstr.WriteDocType("Article", "-//RiQuest Software//DTD JBArticle v1.0 20020724//EN", "../dtd/JBArticle/jbarticle.dtd", null); xTrf.Transform(_extractPath + "/desktop.xml", xTrfArg, mstr); mstr.BaseStream.Flush(); mstr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); return(new StreamReader(mstr.BaseStream).ReadToEnd()); }
public static string xmlNodeToString(System.Xml.XmlNode node, int indentation) { using (var sw = new System.IO.StringWriter()) { using (var xw = new System.Xml.XmlTextWriter(sw)) { xw.Formatting = System.Xml.Formatting.Indented; xw.Indentation = indentation; if (node.ParentNode != null) { node.ParentNode.WriteContentTo(xw); } else { node.WriteContentTo(xw); } } return(sw.ToString()); } }
static void Main() { WebClient client = new WebClient(); //DS--Visual Indicators 1 Console.WriteLine("Application Started, might take a while to Process..."); //DS--Read Url through App.Config string url = ConfigurationManager.AppSettings["TargetUrl"]; //DS--Path and file name to Save as XML from App.config string fileName = ConfigurationManager.AppSettings["FileName"]; fileName = string.Concat(fileName, ".xml"); Stream stream = client.OpenRead(url); //DS--Initializes a new instance of the StreamReader class StreamReader streamReader = new StreamReader(stream); JObject jObject = JObject.Parse(streamReader.ReadLine()); //DS--Visual Indicators Console.WriteLine("JSON Serializing..."); //DS--Create a JSON String string jsonString = JsonConvert.SerializeObject(jObject); //DS--Visual Indicators Console.WriteLine("Xml Conversion Started..."); //DS--JSON to XML Conversion XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonString, "Root"); //DS--Visual Indicators Console.WriteLine("Xml is being Saved, might take a while.."); //DS--Write to a file in XML format System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(fileName, null); xmlTextWriter.Formatting = System.Xml.Formatting.Indented; doc.Save(xmlTextWriter); stream.Close(); }
public void UpdateXmlElement(string XmlfileName, string XmlelementName) { System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(MVVM.Model.Config)); System.IO.StringWriter stringWriter = new System.IO.StringWriter(); System.Xml.XmlWriter xmlWriter = new System.Xml.XmlTextWriter(stringWriter); xmlSerializer.Serialize(xmlWriter, m_config); string newSourceXml = stringWriter.ToString(); XElement newSourceTypeElem = XElement.Parse(newSourceXml); XElement newimport = newSourceTypeElem.Element((XName)XmlelementName); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; try { xmlDoc.Load(XmlfileName); } catch (XmlException e) { Console.WriteLine(e.Message); } // Now create StringWriter object to get data from xml document. StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(sw); xmlDoc.WriteTo(xw); string SourceXml = sw.ToString(); // Replace the current view xml Sources node with the new one XElement viewXmlElem = XElement.Parse(SourceXml); XElement child = viewXmlElem.Element((XName)XmlelementName); // viewXmlElem.Element("importOptions").ReplaceWith(newSourcesElem); child.ReplaceWith(newimport); xmlDoc.LoadXml(viewXmlElem.ToString()); xmlDoc.Save(XmlfileName); }
public void WritePictureXMLFile(List <FileSystemEventArgs> listPictureChanged, bool init = false) { GlobalDataStore.Logger.Debug("Updating Pictures.xml ..."); if (init) { items = new List <LabelX.Toolbox.LabelXItem>(); } //List<LabelX.Toolbox.LabelXItem> items = new List<LabelX.Toolbox.LabelXItem>(); DirectoryInfo PicturesRootFolderDirectoryInfo = new DirectoryInfo(PicturesRootFolder); LabelX.Toolbox.Toolbox.GetPicturesFromFolderTree(PicturesRootFolderDirectoryInfo.FullName, ref items, ref listPictureChanged); //items = alle ingelezen pictures. Nu gaan wegschrijven. System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement root = doc.CreateElement("LabelXItems"); foreach (LabelX.Toolbox.LabelXItem item in items) { System.Xml.XmlElement itemXML = doc.CreateElement("item"); itemXML.SetAttribute("name", item.Name); itemXML.SetAttribute("hash", item.Hash); root.AppendChild(itemXML); } doc.AppendChild(root); MemoryStream ms = new MemoryStream(); System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8); tw.Formatting = System.Xml.Formatting.Indented; doc.WriteContentTo(tw); doc.Save(PicturesRootFolder + "pictures.xml"); tw.Close(); GlobalDataStore.Logger.Debug("Updating Pictures.xml. Done."); }
// Get rid of this function public SymEntry LookupSymbol(Scope scope, string st, bool fMustExist) { SymEntry s = scope.LookupSymbol(st); bool f= false; if (f) { System.Xml.XmlWriter o = new System.Xml.XmlTextWriter(new System.IO.StreamWriter("dump.xml")); scope.Dump(o, true); o.Close(); } if (fMustExist && s == null) { FileRange range = new FileRange(); range.Filename = "<not specified>"; Identifier id = new Identifier(st, range); //ThrowError_UndefinedSymbol(id); ThrowError(SymbolError.UndefinedSymbol(id)); } return s; }
public static string ConvertToXml(object o) { System.IO.StringWriter sw = new System.IO.StringWriter(); System.Xml.XmlTextWriter tw = default(System.Xml.XmlTextWriter); try { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(o.GetType()); tw = new System.Xml.XmlTextWriter(sw); serializer.Serialize(tw, o); return(sw.ToString()); } catch (Exception ex) { return(ex.Message + " " + ex.StackTrace); } finally { sw.Close(); tw.Close(); } }
/// <summary> /// 序列化 对象到字符串; /// 不能序列化IDictionary接口. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string XmlSerialize(object obj) { MemoryStream stream = new MemoryStream(); try { XmlSerializer serializer = new XmlSerializer(obj.GetType()); System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(stream, Encoding.UTF8); serializer.Serialize(xmlTextWriter, obj); stream = (MemoryStream)xmlTextWriter.BaseStream; return(System.Text.Encoding.UTF8.GetString(stream.GetBuffer())); } catch (Exception ex) { throw new Exception("XmlSerialize序列化失败", ex); } finally { stream.Dispose(); } }
static string NodeToString(XmlNode node, int indentation) { try { using (var sw = new System.IO.StringWriter()) { using (var xw = new System.Xml.XmlTextWriter(sw)) { xw.Formatting = System.Xml.Formatting.Indented; xw.Indentation = indentation; node.WriteContentTo(xw); } return(sw.ToString()); } } catch (Exception e) { Console.WriteLine(e.Message); return("Convert to XML error"); } }
public void DeleteAccount(Account account) { foreach (Account ac in _accounts) { if (ac.AccountName == account.AccountName) { _accounts.Remove(ac); break; } } var acc = (from acnt in _accountFile.Descendants("AccountType") where (string)acnt.Attribute("name") == account.AccountName select acnt); acc.Remove(); System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(_fileName, null); writer.Formatting = System.Xml.Formatting.Indented; _accountFile.WriteTo(writer); _reloadAccounts = true; writer.Close(); }
public void DeleteBudget(Budget b) { foreach (Budget budg in _budgets) { if (b.BudgetName == budg.BudgetName) { _budgets.Remove(budg); break; } } var budget = (from bud in _accountFile.Descendants("budget") where (string)bud.Attribute("name") == b.BudgetName select bud); budget.Remove(); System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(_fileName, null); writer.Formatting = System.Xml.Formatting.Indented; _accountFile.WriteTo(writer); _reloadBudgets = true; writer.Close(); }
/// <summary> /// 序列化成xml字符串。用法:List《MyObject》 lMy = new List《MyObject》(); lMy.Add(ceshi); lMy.Add(ceshi2); string s = Serialize(lMy); /// </summary> /// <param name="obj"></param> /// <returns>序列化后的字符串</returns> public static string SerializeCustom(object obj) { //Assembly assembly = typeof() XmlSerializer xs = CreateOverrider(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, System.Text.Encoding.UTF8); xtw.Formatting = System.Xml.Formatting.Indented; xs.Serialize(xtw, obj); ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms)) { string str = sr.ReadToEnd(); xtw.Close(); ms.Close(); return(str); } } }