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(); } }
public void Send(string serviceUrl, string postUrl, string blogName) { try { var request = (HttpWebRequest)WebRequest.Create(serviceUrl); request.Method = "POST"; request.ContentType = "text/xml"; request.Timeout = 3000; request.Credentials = CredentialCache.DefaultNetworkCredentials; var stream = request.GetRequestStream(); using (var writer = new XmlTextWriter(stream, Encoding.ASCII)) { writer.WriteStartDocument(); writer.WriteStartElement("methodCall"); writer.WriteElementString("methodName", "weblogUpdates.ping"); writer.WriteStartElement("params"); writer.WriteStartElement("param"); writer.WriteElementString("value", blogName); writer.WriteEndElement(); writer.WriteStartElement("param"); writer.WriteElementString("value", postUrl); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); } request.GetResponse(); } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(new NotSupportedException()); } }
public static string Serialize(UserProfileData profile) { StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.Formatting = Formatting.Indented; xtw.WriteStartDocument(); xtw.WriteStartElement("user_profile"); xtw.WriteAttributeString("major_version", MAJOR_VERSION.ToString()); xtw.WriteAttributeString("minor_version", MINOR_VERSION.ToString()); xtw.WriteElementString("name", profile.Name); xtw.WriteElementString("id", profile.ID.ToString()); xtw.WriteElementString("about", profile.AboutText); // Not sure if we're storing this yet, need to take a look // xtw.WriteElementString("Url", profile.Url); // or, indeed, interests xtw.WriteEndElement(); xtw.Close(); sw.Close(); return sw.ToString(); }
private static void SaveManToXml(IList<Man> people) { string fileName = "../../peoples.xml"; using (XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.GetEncoding("windows-1251"))) { writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 1; writer.WriteStartDocument(); writer.WriteStartElement("people"); foreach (var man in people) { writer.WriteStartElement("person"); writer.WriteElementString("name", man.Name); writer.WriteElementString("address", man.Address); writer.WriteElementString("phone", man.Phone); writer.WriteEndElement(); } writer.WriteEndElement(); } }
private void GenerateDescription(string host = null) { MemoryStream memStream = new MemoryStream(); using (XmlTextWriter descWriter = new XmlTextWriter(memStream, new UTF8Encoding(false))) { descWriter.Formatting = Formatting.Indented; descWriter.WriteRaw("<?xml version=\"1.0\"?>"); descWriter.WriteStartElement("root", "urn:schemas-upnp-org:device-1-0"); descWriter.WriteStartElement("specVersion"); descWriter.WriteElementString("major", "1"); descWriter.WriteElementString("minor", "0"); descWriter.WriteEndElement(); descWriter.WriteStartElement("device"); rootDevice.WriteDescription(descWriter, host); descWriter.WriteEndElement(); descWriter.WriteEndElement(); descWriter.Flush(); descArray = memStream.ToArray(); } }
private void writeGPX(string filename) { System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".gpx", Encoding.ASCII); xw.WriteStartElement("gpx"); xw.WriteStartElement("trk"); xw.WriteStartElement("trkseg"); foreach (CurrentState cs in flightdata) { xw.WriteStartElement("trkpt"); xw.WriteAttributeString("lat", cs.lat.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteAttributeString("lon", cs.lng.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("ele", cs.alt.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("time", cs.datetime.ToString("yyyy-MM-ddTHH:mm:sszzzzzz")); xw.WriteElementString("course", (cs.yaw).ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("roll", cs.roll.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("pitch", cs.pitch.ToString(new System.Globalization.CultureInfo("en-US"))); //xw.WriteElementString("speed", mod.model.Orientation.); //xw.WriteElementString("fix", cs.altitude); xw.WriteEndElement(); } xw.WriteEndElement(); xw.WriteEndElement(); xw.WriteEndElement(); xw.Close(); }
private void button1_Click(object sender, RoutedEventArgs e) { int dauer = 10; try { dauer = Convert.ToInt32(txt_dauer.Text); } catch (Exception) { } if (!Directory.Exists(Directory.GetCurrentDirectory() + "/quizxml/")) { Directory.CreateDirectory(Directory.GetCurrentDirectory() + "/quizxml/"); } if (File.Exists(Directory.GetCurrentDirectory() + "/quizxml/" + txt_name.Text + ".xml")) { if (!bearbeiten) { MessageBox.Show("Ein Quiz mit diesem Namen existiert bereits! Bitte wählen Sie einen anderen Namen."); return; } } else { XmlTextWriter myXmlTextWriter = new XmlTextWriter(Directory.GetCurrentDirectory() + "/quizxml/" + txt_name.Text + ".xml", System.Text.Encoding.UTF8); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartDocument(false); myXmlTextWriter.WriteStartElement("Quiz"); myXmlTextWriter.WriteElementString("quizname", txt_name.Text); myXmlTextWriter.WriteElementString("sounddatei", txt_name.Text + ".mp3"); myXmlTextWriter.WriteElementString("clipdauer", dauer.ToString()); myXmlTextWriter.WriteElementString("quiztyp", lb_kato.SelectedValue.ToString()); myXmlTextWriter.WriteStartElement("Items"); myXmlTextWriter.WriteEndElement(); myXmlTextWriter.WriteEndElement(); myXmlTextWriter.Close(); bearbeiten = true; } // index = 0 für sound if (lb_kato.SelectedIndex == 0) { MainWindow begriffe_window = new MainWindow(txt_name.Text); begriffe_window.Owner = this; begriffe_window.Show(); } // index = 1 für text if (lb_kato.SelectedIndex == 1) { fragenquiz begriffe_window = new fragenquiz(txt_name.Text); begriffe_window.Owner = this; begriffe_window.Show(); } }
public EndScreen() { InitializeComponent(); try { XmlDocument doc = new XmlDocument(); doc.Load("recentlyPlayed.xml"); XmlNode parent; parent = doc.DocumentElement; //check each child of the parent element foreach (XmlNode child in parent.ChildNodes) { } } catch { XmlTextWriter writer = new XmlTextWriter("recentlyPlayed.xml", null); writer.WriteStartElement("recency"); writer.WriteElementString("winner", ""); writer.WriteElementString("loser", ""); } }
public void HistoryWriting(Result[] results) { foreach (Result result in results) { history.Enqueue(result); } //20개 갯수맞추기 while (true) { if (history.Count <= 20) { break; } history.Dequeue(); } using (XmlTextWriter writer = new XmlTextWriter("../../../Web/static/xml/history.xml", System.Text.Encoding.UTF8)) { writer.WriteStartDocument(); writer.Formatting = Formatting.Indented; writer.Indentation = 2; writer.WriteStartElement("History"); foreach (Result result in Enumerable.Reverse(history)) { writer.WriteStartElement("Info"); writer.WriteElementString("Name", result.name); writer.WriteElementString("Relation", result.relation); writer.WriteElementString("Photo_Path", Path.GetFileName(result.filepath)); if (result.date == null) { writer.WriteElementString("Date", System.DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss")); } else { writer.WriteElementString("Date", System.DateTime.Now.ToString(result.date)); } writer.WriteEndElement(); } writer.Close(); } }
/// <summary> /// The create xml from txt file. /// </summary> /// <param name="txtFile"> /// The txt file. /// </param> public static void CreateXmlFromTxtFile(string txtFile) { // In a text file we are given the name, address and phone number of given person (each at a single line). // Write a program, which creates new XML document, which contains these data in structured XML format. using (var reader = new StreamReader(txtFile)) { using (var writer = new XmlTextWriter(writeFileName, Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 1; writer.WriteStartDocument(); writer.WriteStartElement("data"); writer.WriteStartElement("person"); writer.WriteElementString("name", reader.ReadLine()); writer.WriteElementString("address", reader.ReadLine()); writer.WriteElementString("gsm", reader.ReadLine()); writer.WriteEndElement(); writer.WriteEndDocument(); } } }
public static void Main() { using (XmlTextWriter writer = new XmlTextWriter("../../albums.xml", Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 1; writer.WriteStartDocument(); writer.WriteStartElement("albums"); using (XmlTextReader reader = new XmlTextReader("../../catalog.xml")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "name") { writer.WriteStartElement("album"); writer.WriteElementString("name", reader.ReadElementString()); } if (reader.Name == "artist") { writer.WriteElementString("artist", reader.ReadElementString()); writer.WriteEndElement(); } } } } writer.WriteEndDocument(); } }
public static bool save(SettingsModel settings) { bool result; try { using (XmlTextWriter xmlTextWriter = new XmlTextWriter("settings.xml", Encoding.UTF8)) { xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.Indentation = 4; xmlTextWriter.WriteStartDocument(); xmlTextWriter.WriteStartElement("settings"); xmlTextWriter.WriteElementString("ip", settings.ip); xmlTextWriter.WriteElementString("password", Cryptography.Encrypt(settings.password)); xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteEndDocument(); } result = true; } catch (Exception exception) { LogManager.WriteToLog(exception.Message); result = false; } return result; }
static void WriteAlbum(XmlTextWriter writer, string name, string artist) { writer.WriteStartElement("album"); writer.WriteElementString("name", name); writer.WriteElementString("artist", artist); writer.WriteEndElement(); }
private static void GenerateAlbum() { using (var writer = new XmlTextWriter("../../../AdditionalFiles/album.xml", Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 1; writer.WriteStartDocument(); writer.WriteStartElement("albums"); using (XmlReader reader = XmlReader.Create("../../../AdditionalFiles/catalog.xml")) { while (reader.Read()) { bool isElement = reader.NodeType == XmlNodeType.Element; if (isElement && reader.Name == "name") { writer.WriteStartElement("album"); string albumName = reader.ReadElementContentAsString(); writer.WriteElementString("name", albumName); reader.ReadToFollowing("artist"); string albumAuthor = reader.ReadElementContentAsString(); writer.WriteElementString("author", albumAuthor); writer.WriteEndElement(); } } } writer.WriteEndElement(); } }
static void Main(string[] args) { if (args.Length != 1 || !Directory.Exists(args[0])) { Usage(); return; } string dir = args[0]; XmlTextWriter writer = new XmlTextWriter(PLUGIN_INFO ,Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.Indentation = 3; writer.WriteStartElement("Plugins"); foreach (var file in Directory.GetFiles(dir)) { try { var plugin = Plugin.FromFile(file, false); writer.WriteStartElement("Plugin"); writer.WriteElementString("Version", plugin.Version.ToString()); writer.WriteElementString("Name", plugin.Name); writer.WriteElementString("Description", plugin.Description); writer.WriteElementString("Filename", Path.GetFileName(file)); writer.WriteEndElement(); } catch (Exception e) { Console.WriteLine("Failed to get infor for {0} : {1}", file, e); } } writer.WriteEndElement(); writer.Close(); Console.WriteLine("Wrote data to " + PLUGIN_INFO); }
/// <summary> /// Add an audio track /// </summary> /// <param name="xmlWriter"> /// The xml writer. /// </param> /// <param name="audioTrack"> /// The audio track. /// </param> private static void AddAudioItem(XmlTextWriter xmlWriter, AudioTrack audioTrack) { xmlWriter.WriteStartElement("dict"); xmlWriter.WriteElementString("key", "AudioBitrate"); xmlWriter.WriteElementString("string", audioTrack.Bitrate.ToString()); xmlWriter.WriteElementString("key", "AudioEncoder"); xmlWriter.WriteElementString("string", EnumHelper<AudioEncoder>.GetDisplay(audioTrack.Encoder)); xmlWriter.WriteElementString("key", "AudioMixdown"); xmlWriter.WriteElementString("string", EnumHelper<Mixdown>.GetDisplay(audioTrack.MixDown)); xmlWriter.WriteElementString("key", "AudioSamplerate"); xmlWriter.WriteElementString("string", audioTrack.SampleRate.ToString().Replace("0", "Auto")); xmlWriter.WriteElementString("key", "AudioTrack"); xmlWriter.WriteElementString("integer", audioTrack.Track.ToString()); xmlWriter.WriteElementString("key", "AudioTrackDRCSlider"); xmlWriter.WriteElementString("real", audioTrack.DRC.ToString()); xmlWriter.WriteElementString("key", "AudioTrackDescription"); xmlWriter.WriteElementString("string", "Unknown"); xmlWriter.WriteElementString("key", "AudioTrackGainSlider"); xmlWriter.WriteElementString("real", audioTrack.Gain.ToString()); xmlWriter.WriteEndElement(); }
/// <summary> /// Adds a single item to the XmlTextWriter supplied /// </summary> /// <param name="writer">The XmlTextWriter to be written to</param> /// <param name="sItemTitle">The title of the RSS item</param> /// <param name="sItemLink">The URL of the RSS item</param> /// <param name="sItemDescription">The RSS item text itself</param> /// <param name="sPubDate"></param> /// <param name="bDescAsCdata">Write description as CDATA</param> /// <returns>The XmlTextWriter with the item info written to it</returns> public XmlTextWriter AddRssItem(XmlTextWriter writer, string sItemTitle, string sItemLink, string sItemDescription, DateTime sPubDate, bool bDescAsCdata) { writer.WriteStartElement("item"); writer.WriteElementString("title", sItemTitle); writer.WriteElementString("link", sItemLink); if (bDescAsCdata) { // Now we can write the description as CDATA to support html content. // We find this used quite often in aggregators writer.WriteStartElement("description"); writer.WriteCData(sItemDescription); writer.WriteEndElement(); } else { writer.WriteElementString("description", sItemDescription); } writer.WriteElementString("pubDate", sPubDate.ToString("r")); writer.WriteEndElement(); return writer; }
public bool SettingsWrite(string[] information) { XmlTextWriter xmlWrite = new XmlTextWriter(AppDomain.CurrentDomain.BaseDirectory + "\\settings.xml", System.Text.UTF8Encoding.UTF8); xmlWrite.Formatting = Formatting.Indented; try { xmlWrite.WriteStartDocument(); xmlWrite.WriteStartElement("root"); xmlWrite.WriteStartElement("settings"); xmlWrite.WriteElementString("server", information[0]); xmlWrite.WriteElementString("cache", information[1]); xmlWrite.WriteEndElement(); xmlWrite.WriteEndElement(); xmlWrite.Close(); DNS dns = new DNS(); dns._resolver.DnsServer = information[0]; dns._resolver.UseCache = Convert.ToBoolean(information[1]); return true; } catch (Exception ex) { Console.WriteLine("XML Error: " + ex.Message); return false; } }
/// <summary> /// /// </summary> /// <param name="coordinate"></param> /// <param name="writer"></param> protected void Write(ICoordinate coordinate, XmlTextWriter writer) { writer.WriteStartElement(GMLElements.gmlPrefix, "coord", GMLElements.gmlNS); writer.WriteElementString(GMLElements.gmlPrefix, "X", GMLElements.gmlNS, coordinate.X.ToString("g", NumberFormatter)); writer.WriteElementString(GMLElements.gmlPrefix, "Y", GMLElements.gmlNS, coordinate.Y.ToString("g", NumberFormatter)); writer.WriteEndElement(); }
public static void ConvetTextToXml() { string[] lines; const int NumberOfTagsForEachPerson = 3; using (var writer = new XmlTextWriter("../../toXml.xml", Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 1; using (StreamReader reader = new StreamReader("../../fromText.txt")) { lines = reader.ReadToEnd().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); writer.WriteStartDocument(); writer.WriteStartElement("Persons"); for (int i = 0; i < lines.Length; i += NumberOfTagsForEachPerson) { writer.WriteStartElement("Person"); writer.WriteElementString("name", lines[i]); writer.WriteElementString("adress", lines[i + 1]); writer.WriteElementString("telephone", lines[i + 2]); writer.WriteEndElement(); } writer.WriteEndElement(); } } Console.WriteLine("\tDONE!!! Check file!"); }
private void PingService(string ping, string name, string url) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ping); request.Method = "POST"; request.ContentType = "text/xml"; using (Stream stream = (Stream)request.GetRequestStream()) { using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.UTF8)) { xml.WriteStartDocument(); xml.WriteStartElement("methodCall"); xml.WriteElementString("methodName", "weblogUpdates.ping"); xml.WriteStartElement("params"); xml.WriteStartElement("param"); xml.WriteElementString("value", name); xml.WriteEndElement(); xml.WriteStartElement("param"); xml.WriteElementString("value", url); xml.WriteEndElement(); xml.WriteEndElement(); xml.WriteEndElement(); xml.WriteEndDocument(); } } } catch (Exception ex) { Log.Add(LogTypes.Debug, -1, "pinger: url: " + ping + " exception:" + ex.ToString()); } }
/// <summary> /// Adds the XML to web request. The XML is the standard /// XML used by RPC-XML requests. /// </summary> private static void AddXmlToRequest(Uri sourceUrl, Uri targetUrl, HttpWebRequest webreqPing) { Stream stream = (Stream)webreqPing.GetRequestStream(); using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.ASCII)) { writer.WriteStartDocument(true); writer.WriteStartElement("methodCall"); writer.WriteElementString("methodName", "pingback.ping"); writer.WriteStartElement("params"); writer.WriteStartElement("param"); writer.WriteStartElement("value"); writer.WriteElementString("string", sourceUrl.ToString()); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteStartElement("param"); writer.WriteStartElement("value"); writer.WriteElementString("string", targetUrl.ToString()); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); } }
static void Main() { string fileName = "../../album.xml"; Encoding encoding = Encoding.GetEncoding("windows-1251"); using (XmlTextWriter writer = new XmlTextWriter(fileName, encoding)) { writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 2; writer.WriteStartDocument(); writer.WriteStartElement("albums"); using (XmlReader reader = XmlReader.Create("../../../catalogue.xml")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "name") { writer.WriteStartElement("album"); writer.WriteElementString("name", reader.ReadElementString()); } else if (reader.NodeType == XmlNodeType.Element && reader.Name == "artist") { writer.WriteElementString("artist", reader.ReadElementString()); writer.WriteEndElement(); } } } Console.WriteLine("Finish"); } }
private static void Main(string[] args) { // 8. Write a program, which (using XmlReader and XmlWriter) reads the file catalog.xml and creates the file album.xml, // in which stores in appropriate way the names of all albums and their authors Encoding encoding = Encoding.UTF8; using (XmlTextWriter writer = new XmlTextWriter(FileToWrite, encoding)) { writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 1; writer.WriteStartDocument(); writer.WriteStartElement("albums"); using (XmlTextReader reader = new XmlTextReader(FileToRead)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "name") { writer.WriteStartElement("album"); writer.WriteElementString("name", reader.ReadElementString()); } else if (reader.NodeType == XmlNodeType.Element && reader.Name == "artist") { writer.WriteElementString("artist", reader.ReadElementString()); writer.WriteEndElement(); } } } writer.WriteEndDocument(); } }
/// <summary> /// Export Products To Google Base /// </summary> /// <returns></returns> public byte[] ExportProductsToGoogleBase() { const string ns = "http://base.google.com/ns/1.0"; var ms = new MemoryStream(); var xml = new XmlTextWriter(ms, Encoding.UTF8); xml.WriteStartDocument(); xml.WriteStartElement("rss"); xml.WriteAttributeString("xmlns", "g", null, ns); xml.WriteAttributeString("version", "2.0"); xml.WriteStartElement("channel"); //GENERAL FEED INFO xml.WriteElementString("title", CurrentRequestData.CurrentSite.Name); xml.WriteElementString("link", CurrentRequestData.CurrentSite.BaseUrl); xml.WriteElementString("description", " Products from " + CurrentRequestData.CurrentSite.Name + " online store"); IList<ProductVariant> productVariants = _productVariantService.GetAllVariantsForGoogleBase(); foreach (ProductVariant pv in productVariants) { ExportGoogleBaseProduct(ref xml, pv, ns); } xml.WriteEndElement(); xml.WriteEndElement(); xml.WriteEndDocument(); xml.Flush(); byte[] file = ms.ToArray(); xml.Close(); return file; }
static void Main(string[] args) { using (XmlTextWriter writer = new XmlTextWriter(OutputPath, Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.IndentChar = ' '; writer.WriteStartDocument(); writer.WriteStartElement("albums"); using (XmlReader reader = XmlReader.Create(InputPath)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "name") { writer.WriteStartElement("album"); writer.WriteElementString("name", reader.ReadElementString()); } else if (reader.Name == "artist") { writer.WriteElementString("artist", reader.ReadElementString()); writer.WriteEndElement(); } } } } writer.WriteEndDocument(); } Console.WriteLine("Parsing is finished. Your document is ready."); }
static void ImportXMLfile(int popMember) { string filename = ""; filename = GlobalVar.jobName + GlobalVar.popIndex.ToString() + popMember.ToString(); XmlTextWriter xml = null; xml = new XmlTextWriter(filename, null); xml.WriteStartDocument(); xml.WriteStartElement("Features"); xml.WriteWhitespace("\n"); for (int i = 0; i < GlobalVar.featureCount; i++) { xml.WriteElementString("Index", i.ToString()); xml.WriteElementString("Value", GlobalVar.features[i].ToString()); xml.WriteWhitespace("\n "); } xml.WriteEndElement(); xml.WriteWhitespace("\n"); xml.WriteEndDocument(); //Write the XML to file and close the writer. xml.Flush(); xml.Close(); }
public static void Main() { XmlReader reader = XmlReader.Create("..\\..\\..\\XmlCatalogDirectory\\text.xml"); XmlTextWriter writer = new XmlTextWriter("..\\..\\album.xml",Encoding.UTF8); using (writer) { writer.WriteStartDocument(); writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 1; writer.WriteStartElement("albums"); string artist = ""; while (reader.Read()) { if ((reader.NodeType == XmlNodeType.Element) && reader.Name == "artist") { artist = reader.GetAttribute("name"); } else if ((reader.NodeType == XmlNodeType.Element) && reader.Name == "name") { string albumName = reader.ReadElementContentAsString(); writer.WriteStartElement("album"); writer.WriteElementString("name", albumName); writer.WriteElementString("artist", artist); writer.WriteEndElement(); } } } }
private static void PingServices(IEnumerable<Uri> Services, Uri Blog, string BlogName) { foreach (Uri Service in Services) { HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Service); Request.Credentials = CredentialCache.DefaultNetworkCredentials; Request.ContentType = "text/xml"; Request.Method = "POST"; Request.Timeout = 10000; using (XmlTextWriter XMLWriter = new XmlTextWriter(Request.GetRequestStream(), Encoding.ASCII)) { XMLWriter.WriteStartDocument(); XMLWriter.WriteStartElement("methodCall"); XMLWriter.WriteElementString("methodName", "weblogUpdates.ping"); XMLWriter.WriteStartElement("params"); XMLWriter.WriteStartElement("param"); XMLWriter.WriteElementString("value", BlogName); XMLWriter.WriteEndElement(); XMLWriter.WriteStartElement("param"); XMLWriter.WriteElementString("value", Blog.ToString()); XMLWriter.WriteEndElement(); XMLWriter.WriteEndElement(); XMLWriter.WriteEndElement(); } } }
/// <summary> /// 写入配置参数数据 /// </summary> /// <param name="Path"></param> public void WriterXml(string Path) { try { // 创建XmlTextWriter类的实例对象 XmlTextWriter textWriter = new XmlTextWriter(Path, null); textWriter.Formatting = Formatting.Indented; // 开始写过程,调用WriteStartDocument方法 textWriter.WriteStartDocument(); // 写入说明 textWriter.WriteComment("First Comment XmlTextWriter Sample Example"); textWriter.WriteComment("w3sky.xml in root dir"); //创建一个节点 textWriter.WriteStartElement("Administrator"); textWriter.WriteElementString("Name", "formble"); textWriter.WriteElementString("site", "w3sky.com"); textWriter.WriteEndElement(); // 写文档结束,调用WriteEndDocument方法 textWriter.WriteEndDocument(); // 关闭textWriter textWriter.Close(); } catch (System.Exception e) { Console.WriteLine(e.ToString()); } }
/// ----------------------------------------------------------------------------- /// <summary> /// builds XML access key for UPS requests /// </summary> /// <param name="settings"></param> /// <returns></returns> /// <remarks> /// </remarks> /// <history> /// [mmcconnell] 11/1/2004 Created /// </history> /// ----------------------------------------------------------------------------- public static string BuildAccessKey(UpsSettings settings) { string sXML = ""; StringWriter strWriter = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(strWriter); xw.Formatting = Formatting.Indented; xw.Indentation = 3; xw.WriteStartDocument(); //-------------------------------------------- // Agreement Request xw.WriteStartElement("AccessRequest"); xw.WriteElementString("AccessLicenseNumber", settings.License); xw.WriteElementString("UserId", settings.UserID); xw.WriteElementString("Password", settings.Password); xw.WriteEndElement(); // End Agreement Request //-------------------------------------------- xw.WriteEndDocument(); xw.Flush(); xw.Close(); sXML = strWriter.GetStringBuilder().ToString(); xw = null; //HttpContext.Current.Trace.Write("AccessRequest=" & sXML) return sXML; }
private void SavePluginListToXMLFile(string filename) { try { Console.WriteLine("Saving plugins entries to " + (string)MediaNET.Config["Interface/plugins.xml"]); XmlTextWriter writer = new System.Xml.XmlTextWriter((string)MediaNET.Config["Interface/plugins.xml"], null); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("plugins"); TreeModel model = pluginList.Model; TreeIter iter; if (pluginStore.GetIterFirst(out iter)) { do { writer.WriteStartElement("plugin"); writer.WriteElementString("extension", (string)model.GetValue(iter, 0)); // Second field ignored -> found using reflection writer.WriteElementString("player", (string)model.GetValue(iter, 2)); writer.WriteElementString("path", (string)model.GetValue(iter, 3)); writer.WriteEndElement(); }while (pluginStore.IterNext(ref iter)); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); writer.Close(); } catch (Exception e) { throw new Exception("Save settings failed: " + e.Message); } }
public static void SaveToXml(System.Xml.XmlTextWriter xmlWriter, IImageSet imageset, string alternateUrl) { xmlWriter.WriteStartElement("ImageSet"); xmlWriter.WriteAttributeString("Generic", imageset.Generic.ToString()); xmlWriter.WriteAttributeString("DataSetType", imageset.DataSetType.ToString()); xmlWriter.WriteAttributeString("BandPass", imageset.BandPass.ToString()); if (!imageset.Generic) { xmlWriter.WriteAttributeString("Name", imageset.Name); if (String.IsNullOrEmpty(alternateUrl)) { xmlWriter.WriteAttributeString("Url", imageset.Url); } else { xmlWriter.WriteAttributeString("Url", alternateUrl); } xmlWriter.WriteAttributeString("DemUrl", imageset.DemUrl); xmlWriter.WriteAttributeString("BaseTileLevel", imageset.BaseLevel.ToString()); xmlWriter.WriteAttributeString("TileLevels", imageset.Levels.ToString()); xmlWriter.WriteAttributeString("BaseDegreesPerTile", imageset.BaseTileDegrees.ToString()); xmlWriter.WriteAttributeString("FileType", imageset.Extension); xmlWriter.WriteAttributeString("BottomsUp", imageset.BottomsUp.ToString()); xmlWriter.WriteAttributeString("Projection", imageset.Projection.ToString()); xmlWriter.WriteAttributeString("QuadTreeMap", imageset.QuadTreeTileMap); xmlWriter.WriteAttributeString("CenterX", imageset.CenterX.ToString()); xmlWriter.WriteAttributeString("CenterY", imageset.CenterY.ToString()); xmlWriter.WriteAttributeString("OffsetX", imageset.OffsetX.ToString()); xmlWriter.WriteAttributeString("OffsetY", imageset.OffsetY.ToString()); xmlWriter.WriteAttributeString("Rotation", imageset.Rotation.ToString()); xmlWriter.WriteAttributeString("Sparse", imageset.Sparse.ToString()); xmlWriter.WriteAttributeString("ElevationModel", imageset.ElevationModel.ToString()); xmlWriter.WriteAttributeString("StockSet", imageset.DefaultSet.ToString()); xmlWriter.WriteAttributeString("WidthFactor", imageset.WidthFactor.ToString()); xmlWriter.WriteAttributeString("MeanRadius", imageset.MeanRadius.ToString()); xmlWriter.WriteAttributeString("ReferenceFrame", imageset.ReferenceFrame); if (String.IsNullOrEmpty(alternateUrl)) { xmlWriter.WriteElementString("ThumbnailUrl", imageset.ThumbnailUrl); } else { xmlWriter.WriteElementString("ThumbnailUrl", imageset.Url); } } xmlWriter.WriteEndElement(); }
public static void WriteXmlInFile(string layer, string msg) { try { //XmlDataDocument sourceXML = new XmlDataDocument(); string xmlFile = HttpContext.Current.Server.MapPath("/log/Exception.xml"); //create a XML file is not exist System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(xmlFile, null); //starts a new document writer.WriteStartDocument(); //write comments writer.WriteComment("Commentss: XmlWriter Test Program"); writer.Formatting = Formatting.Indented; writer.WriteStartElement("MessageList"); writer.WriteStartElement("Exception"); writer.WriteAttributeString("Layer", layer); //write some simple elements writer.WriteElementString("Message", msg); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.Close(); } catch (Exception ex) { throw ex; } }
public void SaveV1PeakParameters(System.Xml.XmlTextWriter xwriter) { xwriter.WriteWhitespace("\n\t"); xwriter.WriteStartElement("PeakParameters"); xwriter.WriteWhitespace("\n\t\t"); xwriter.WriteElementString("PeakBackgroundRatio", System.Convert.ToString(this.PeakBackgroundRatio)); xwriter.WriteWhitespace("\n\t\t"); xwriter.WriteElementString("SignalToNoiseThreshold", this.SignalToNoiseThreshold.ToString()); xwriter.WriteWhitespace("\n\t\t"); xwriter.WriteElementString("PeakFitType", this.PeakFitType.ToString()); xwriter.WriteWhitespace("\n\t\t"); xwriter.WriteElementString("WritePeaksToTextFile", this.WritePeaksToTextFile.ToString()); xwriter.WriteWhitespace("\n\t"); xwriter.WriteEndElement(); }
public virtual void SaveToXml(System.Xml.XmlTextWriter xmlWriter) { xmlWriter.WriteStartElement("ReferenceFrame"); xmlWriter.WriteAttributeString("Name", Name); xmlWriter.WriteAttributeString("Parent", Parent); xmlWriter.WriteAttributeString("ReferenceFrameType", ReferenceFrameType.ToString()); xmlWriter.WriteAttributeString("Reference", Reference.ToString()); xmlWriter.WriteAttributeString("ParentsRoationalBase", ParentsRoationalBase.ToString()); xmlWriter.WriteAttributeString("MeanRadius", MeanRadius.ToString()); xmlWriter.WriteAttributeString("Oblateness", Oblateness.ToString()); xmlWriter.WriteAttributeString("Heading", Heading.ToString()); xmlWriter.WriteAttributeString("Pitch", Pitch.ToString()); xmlWriter.WriteAttributeString("Roll", Roll.ToString()); xmlWriter.WriteAttributeString("Scale", Scale.ToString()); xmlWriter.WriteAttributeString("Tilt", Tilt.ToString()); xmlWriter.WriteAttributeString("Translation", Translation.ToString()); if (ReferenceFrameType == ReferenceFrameTypes.FixedSherical) { xmlWriter.WriteAttributeString("Lat", Lat.ToString()); xmlWriter.WriteAttributeString("Lng", Lng.ToString()); xmlWriter.WriteAttributeString("Altitude", Altitude.ToString()); } xmlWriter.WriteAttributeString("RotationalPeriod", RotationalPeriod.ToString()); xmlWriter.WriteAttributeString("ZeroRotationDate", ZeroRotationDate.ToString()); xmlWriter.WriteAttributeString("RepresentativeColor", SavedColor.Save(RepresentativeColor)); xmlWriter.WriteAttributeString("ShowAsPoint", ShowAsPoint.ToString()); xmlWriter.WriteAttributeString("ShowOrbitPath", ShowOrbitPath.ToString()); xmlWriter.WriteAttributeString("StationKeeping", StationKeeping.ToString()); if (ReferenceFrameType == ReferenceFrameTypes.Orbital) { xmlWriter.WriteAttributeString("SemiMajorAxis", SemiMajorAxis.ToString()); xmlWriter.WriteAttributeString("SemiMajorAxisScale", this.SemiMajorAxisUnits.ToString()); xmlWriter.WriteAttributeString("Eccentricity", Eccentricity.ToString()); xmlWriter.WriteAttributeString("Inclination", Inclination.ToString()); xmlWriter.WriteAttributeString("ArgumentOfPeriapsis", ArgumentOfPeriapsis.ToString()); xmlWriter.WriteAttributeString("LongitudeOfAscendingNode", LongitudeOfAscendingNode.ToString()); xmlWriter.WriteAttributeString("MeanAnomolyAtEpoch", MeanAnomolyAtEpoch.ToString()); xmlWriter.WriteAttributeString("MeanDailyMotion", MeanDailyMotion.ToString()); xmlWriter.WriteAttributeString("Epoch", Epoch.ToString()); } if (ReferenceFrameType == ReferenceFrameTypes.Trajectory) { xmlWriter.WriteStartElement("Trajectory"); foreach (TrajectorySample sample in Trajectory) { string data = sample.ToString(); xmlWriter.WriteElementString("Sample", data); } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); }
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 }
///<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(); }
public void WriteValue(string strSection, string strKey, string strValue) { //XmlNodeList mNode = mXml.GetElementsByTagName(strSection); XmlTextWriter mXmlWrite = new System.Xml.XmlTextWriter(this.strPathOfXml, System.Text.UTF8Encoding.UTF8); mXmlWrite.Formatting = Formatting.Indented; mXmlWrite.WriteStartDocument(); mXmlWrite.WriteStartElement("property"); mXmlWrite.WriteStartElement(strSection); mXmlWrite.WriteElementString(strKey, strValue); mXmlWrite.WriteEndElement(); mXmlWrite.WriteEndElement(); mXmlWrite.WriteEndDocument(); mXmlWrite.Flush(); mXmlWrite.Close(); }
/// <summary> /// Writes the XML element. /// </summary> /// <param name="writer">The writer.</param> virtual protected void WriteXMLElement(System.Xml.XmlTextWriter writer) { writer.WriteAttributeString("type", this.ResourceType.Name); writer.WriteAttributeString("name", _name); writer.WriteAttributeString("id", ID.ToString()); writer.WriteElementString("family", (Parent != null) ? Parent.QualifiedName : ""); foreach (FieldValueList fieldValues in this.Fields.Values) { foreach (object v in fieldValues.Values) { writer.WriteStartElement("field"); writer.WriteAttributeString("name", fieldValues.Type.Name); writer.WriteValue(v.ToString()); writer.WriteEndElement(); } } }
private void SaveXmlCommandFile(string filename) { if (this.MergeListFileArray.Count < 1) { return; } System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(filename, new System.Text.UnicodeEncoding()); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("merge"); // Write sub-elements foreach (MergeListFiles mergeItem in this.MergeListFileArray) { writer.WriteStartElement("file"); if (mergeItem.Include == false) { writer.WriteAttributeString("exclude", "1"); } writer.WriteElementString("path", mergeItem.Path); writer.WriteElementString("pages", mergeItem.Pages); if (mergeItem.Bookmark != null) { writer.WriteElementString("bookmark", mergeItem.Bookmark); } if (mergeItem.Level > 0) { writer.WriteElementString("level", XmlConvert.ToString(mergeItem.Level)); } writer.WriteEndElement(); } #region write info and options if (this.MergeListInfo.HasInfo == true) { writer.WriteStartElement("info"); if (this.MergeListInfo.InfoAuthor.Length > 0) { writer.WriteElementString("author", this.MergeListInfo.InfoAuthor); } if (this.MergeListInfo.InfoSubject.Length > 0) { writer.WriteElementString("subject", this.MergeListInfo.InfoSubject); } if (this.MergeListInfo.InfoTitle.Length > 0) { writer.WriteElementString("title", this.MergeListInfo.InfoTitle); } writer.WriteEndElement(); } writer.WriteStartElement("options"); if (string.IsNullOrEmpty(this.MergeListInfo.OutFilename) == false) { writer.WriteElementString("outfile", this.MergeListInfo.OutFilename); } if (string.IsNullOrEmpty(this.MergeListInfo.Annotation) == false) { writer.WriteElementString("annotation", this.MergeListInfo.Annotation); } if (this.MergeListInfo.NumberPages == true) { writer.WriteElementString("startpage", this.MergeListInfo.StartPage.ToString()); } writer.WriteElementString("paginationformat", ((int)this.MergeListInfo.PaginationFormat).ToString()); writer.WriteEndElement(); #endregion writer.WriteFullEndElement(); writer.Close(); }
protected override void OutputResults(TestResultGrp resultGrp, object[] ConfigSettings) { TestResult[] Results = resultGrp.Results; string procName = ""; uint L2CacheSize = 0; uint L2CacheSpeed = 0; int procNo = 0; ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT Name, L2CacheSize, L2CacheSpeed FROM Win32_Processor"); ManagementObjectCollection moc = mos.Get(); foreach (ManagementObject mob in moc) { ++procNo; procName = mob.Properties["Name"].Value.ToString(); L2CacheSize = Convert.ToUInt32(mob.Properties["L2CacheSize"].Value); L2CacheSpeed = Convert.ToUInt32(mob.Properties["L2CacheSpeed"].Value); } if (Results == null) { return; } string xmlFileName = (string)ConfigSettings[0]; if (xmlFileName == String.Empty) { xmlFileName = "c:\\" + resultGrp.TestName + ".xml"; } System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(xmlFileName, System.Text.Encoding.UTF8); writer.WriteStartElement("testresults"); writer.WriteAttributeString("Name", resultGrp.TestName); if (resultGrp.Motivation != String.Empty) { writer.WriteAttributeString("Motivation", resultGrp.Motivation); } writer.WriteAttributeString("TestTime", DateTime.UtcNow.ToString("r")); writer.WriteAttributeString("MachineName", System.Environment.MachineName); writer.WriteAttributeString("CLR_Version", System.Environment.Version.ToString()); writer.WriteAttributeString("OS", System.Environment.OSVersion.ToString()); writer.WriteAttributeString("NoProcessors", procNo.ToString()); writer.WriteAttributeString("ProcName", procName); writer.WriteAttributeString("L2CacheSize_Kilobytes", L2CacheSize.ToString()); writer.WriteAttributeString("L2CacheSpeed_MegaHertz", L2CacheSpeed.ToString()); foreach (DotNetPerformance.TestResult tr in Results) { writer.WriteStartElement("testresult"); writer.WriteAttributeString("Name", tr.TestName); writer.WriteAttributeString("Min", tr.Min.TotalMilliseconds.ToString()); writer.WriteAttributeString("Median", tr.Median.TotalMilliseconds.ToString()); writer.WriteAttributeString("Max", tr.Max.TotalMilliseconds.ToString()); writer.WriteAttributeString("NormalizedTestDuration", tr.NormalizedTestDuration.ToString()); foreach (TimeSpan ts in tr.TestResults) { writer.WriteElementString("testrun", ts.TotalMilliseconds.ToString()); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.Close(); System.Diagnostics.Process.Start(xmlFileName); }
private void GeneraXML(System.Xml.XmlTextWriter writer) // As System.Xml.XmlTextWriter { try { writer.WriteStartDocument(); writer.WriteStartElement("FacturaElectronica"); writer.WriteAttributeString("xmlns", "https://tribunet.hacienda.go.cr/docs/esquemas/2017/v4.2/facturaElectronica"); writer.WriteAttributeString("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); writer.WriteAttributeString("xmlns:vc", "http://www.w3.org/2007/XMLSchema-versioning"); writer.WriteAttributeString("xmlns:xs", "http://www.w3.org/2001/XMLSchema"); // La clave se crea con la función CreaClave de la clase Datos writer.WriteElementString("Clave", _numeroClave); // 'El numero de secuencia es de 20 caracteres, // 'Se debe de crear con la función CreaNumeroSecuencia de la clase Datos writer.WriteElementString("NumeroConsecutivo", _numeroConsecutivo); // 'El formato de la fecha es yyyy-MM-ddTHH:mm:sszzz writer.WriteElementString("FechaEmision", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")); writer.WriteStartElement("Emisor"); writer.WriteElementString("Nombre", _emisor.Nombre); writer.WriteStartElement("Identificacion"); writer.WriteElementString("Tipo", _emisor.Tipo_Identificacion); writer.WriteElementString("Numero", _emisor.Numero_Identificacion); writer.WriteEndElement(); // 'Identificacion // '----------------------------------- // 'Los datos de las ubicaciones los puede tomar de las tablas de datos, // 'Debe ser exacto al que hacienda tiene registrado para su compañia writer.WriteStartElement("Ubicacion"); writer.WriteElementString("Provincia", _emisor.Provincia); writer.WriteElementString("Canton", _emisor.Canton); writer.WriteElementString("Distrito", _emisor.Distrito); writer.WriteElementString("Barrio", _emisor.Barrio); writer.WriteElementString("OtrasSenas", _emisor.OtrasSenas); writer.WriteEndElement(); // 'Ubicacion writer.WriteStartElement("Telefono"); writer.WriteElementString("CodigoPais", _emisor.CodigoPaisTel); writer.WriteElementString("NumTelefono", _emisor.NumTelefono.ToString()); writer.WriteEndElement(); // 'Telefono writer.WriteElementString("CorreoElectronico", _emisor.CorreoElectronico); writer.WriteEndElement(); // Emisor // '------------------------------------ // 'Receptor es similar con emisor, los datos opcionales siempre siempre siempre omitirlos. // 'La ubicacion para el receptor es opcional por ejemplo writer.WriteStartElement("Receptor"); writer.WriteElementString("Nombre", _receptor.Nombre); writer.WriteStartElement("Identificacion"); // 'Los tipos de identificacion los puede ver en la tabla de datos writer.WriteElementString("Tipo", _receptor.Tipo_Identificacion); writer.WriteElementString("Numero", _receptor.Numero_Identificacion); writer.WriteEndElement(); // 'Identificacion writer.WriteStartElement("Telefono"); writer.WriteElementString("CodigoPais", _receptor.CodigoPaisTel); writer.WriteElementString("NumTelefono", _receptor.NumTelefono.ToString()); writer.WriteEndElement(); // 'Telefono writer.WriteElementString("CorreoElectronico", _receptor.CorreoElectronico); writer.WriteEndElement(); // Receptor // '------------------------------------ // 'Loa datos estan en la tabla correspondiente writer.WriteElementString("CondicionVenta", _condicionVenta); // '01: Contado // '02: Credito // '03: Consignación // '04: Apartado // '05: Arrendamiento con opcion de compra // '06: Arrendamiento con función financiera // '99: Otros // 'Este dato se muestra si la condicion venta es credito writer.WriteElementString("PlazoCredito", _plazoCredito); writer.WriteElementString("MedioPago", _medioPago); // '01: Efectivo // '02: Tarjeta // '03: Cheque // '04: Transferecia - deposito bancario // '05: Recaudado por terceros // '99: Otros writer.WriteStartElement("DetalleServicio"); // '------------------------------------- /* foreach (DataRow dr in _dsDetalle.Tables["detalle"].Rows) * { * writer.WriteStartElement("LineaDetalle"); * * writer.WriteElementString("NumeropLinea", dr["numero_linea"].ToString()); * * writer.WriteStartElement("Codigo"); * writer.WriteElementString("Tipo", dr["articulo_tipo"].ToString()); * writer.WriteElementString("Codigo", dr["articulo_codigo"].ToString()); * writer.WriteEndElement(); // 'Codigo * * writer.WriteElementString("Cantidad", dr["cantidad"].ToString()); * // 'Para las unidades de medida ver la tabla correspondiente * writer.WriteElementString("UnidadMedida", dr["unidad_medida"].ToString()); * writer.WriteElementString("Detalle", dr["detalle_articulo"].ToString()); * writer.WriteElementString("PrecioUnitario", String.Format("{0:N3}", dr["precio_unitario"].ToString())); * writer.WriteElementString("MontoTotal", String.Format("{0:N3}", dr["monto_total"].ToString())); * writer.WriteElementString("MontoDescuento", String.Format("{0:N3}", dr["nonto_descuento"].ToString())); * writer.WriteElementString("NaturalezaDescuento", dr["naturaleza_descuento"].ToString()); * writer.WriteElementString("SubTotal", String.Format("{0:N3}", dr["sub_total"].ToString())); * * writer.WriteStartElement("Impuesto"); * writer.WriteElementString("Codigo", dr["impuesto_codigo"].ToString()); * writer.WriteElementString("Tarifa", dr["impuesto_tarifa"].ToString()); * writer.WriteElementString("Monto", dr["impuesto_monto"].ToString()); * writer.WriteEndElement(); // Impuesto * * writer.WriteElementString("MontoTotalLinea", String.Format("{0:N3}", dr["monto_linea"].ToString())); * * writer.WriteEndElement(); // LineaDetalle * } * // '------------------------------------- * * writer.WriteEndElement(); // DetalleServicio*/ writer.WriteStartElement("ResumenFactura"); // Estos campos son opcionales, solo fin desea facturar en dólares //writer.WriteElementString("CodigoMoneda", _codigoMoneda); // writer.WriteElementString("TipoCambio", "aqui_tipo_cambio"); // ================= // 'En esta parte los totales se pueden ir sumando linea a linea cuando se carga el detalle // 'ó se pasa como parametros al inicio writer.WriteElementString("TotalServGravados", ""); writer.WriteElementString("TotalServExentos", ""); writer.WriteElementString("TotalMercanciasGravadas", ""); writer.WriteElementString("TotalMercanciasExentas", ""); writer.WriteElementString("TotalGravado", ""); writer.WriteElementString("TotalExento", ""); writer.WriteElementString("TotalVenta", ""); writer.WriteElementString("TotalDescuentos", ""); writer.WriteElementString("TotalVentaNeta", ""); writer.WriteElementString("TotalImpuesto", ""); writer.WriteElementString("TotalComprobante", ""); writer.WriteEndElement(); // ResumenFactura // 'Estos datos te los tiene que brindar los encargados del area financiera writer.WriteStartElement("Normativa"); writer.WriteElementString("NumeroResolucion", ""); writer.WriteElementString("FechaResolucion", ""); writer.WriteEndElement(); // Normativa // 'Aqui va la firma, despues la agregamos. writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); } catch (Exception ex) { throw ex; } }
private void Write_XML() { XmlTextWriter XmlWtr = new System.Xml.XmlTextWriter("..\\..\\..\\xml\\lh_giostt.xml", null); //XmlFile XmlWtr.Formatting = Formatting.Indented; XmlWtr.WriteStartDocument(); XmlWtr.WriteStartElement("Import"); h_start = int.Parse(cmbgbd.Text.Substring(0, 2)); m_start = int.Parse(cmbpbd.Text.Substring(0, 2)); h_end = int.Parse(cmbgkt.Text.Substring(0, 2)); m_end = int.Parse(cmbpkt.Text.Substring(0, 2)); int khoangcachthoigian; if (rdob10.Checked) { khoangcachthoigian = 10; } else { if (rdob5.Checked) { khoangcachthoigian = 5; } else { khoangcachthoigian = 7; } } for (hours = h_start; hours <= h_end; hours++) { counts++; if (counts == 1) { //pbd=int.Parse(cmbpbd.Text.Substring(0,2)); m_start = int.Parse("00"); //pkt=55; m_end = 59; } else { m_start = 0; //pkt=55; m_end = 59; } if ((counts + h_start) == (h_end + 1)) { m_start = 0; //pkt=int.Parse(cmbpkt.Text.Substring(0,2)); m_end = int.Parse("30"); } for (minutes = m_start; minutes <= m_end; minutes = minutes + 1) { lan++; if (hours.ToString().Length == 1) { wss = "0" + hours.ToString(); } else { wss = hours.ToString(); } if (minutes.ToString().Length == 1) { qss = "0" + minutes.ToString(); } else { qss = minutes.ToString(); } ass = wss + ":" + qss; XmlWtr.WriteStartElement("Giolam"); XmlWtr.WriteElementString("Gio", ass); XmlWtr.WriteElementString("Sothutu", stt.ToString()); XmlWtr.WriteElementString("Thoigiantb", khoangcachthoigian.ToString()); if (lan == khoangcachthoigian) { stt++; lan = 0; } XmlWtr.WriteEndElement(); } } XmlWtr.Flush(); XmlWtr.Close(); }
private void WriteXML() { // string XmlFile; // System.IO.DirectoryInfo directoryInfo; // System.IO.DirectoryInfo directoryXML; // directoryInfo = System.IO.Directory.GetParent(Application.StartupPath); // if (directoryInfo.Name.ToString() == "bin") // { // directoryXML = System.IO.Directory.GetParent(directoryInfo.FullName); // XmlFile = directoryXML.FullName + "\\" + "gio.xml"; // } // else // XmlFile = directoryInfo.FullName + "\\" + "gio.xml"; XmlTextWriter XmlWtr = new System.Xml.XmlTextWriter("..\\..\\..\\xml\\lh_gio.xml", null); //XmlFile XmlWtr.Formatting = Formatting.Indented; XmlWtr.WriteStartDocument(); XmlWtr.WriteStartElement("Import"); gbd = int.Parse(cmbgbd.Text.Substring(0, 2)); pbd = int.Parse(cmbpbd.Text.Substring(0, 2)); gkt = int.Parse(cmbgkt.Text.Substring(0, 2)); pkt = int.Parse(cmbpkt.Text.Substring(0, 2)); for (gio = gbd; gio <= gkt; gio++) { count++; if (count == 1) { pbd = int.Parse(cmbpbd.Text.Substring(0, 2)); pkt = 55; } else { pbd = 0; pkt = 55; } if ((count + gbd) == (gkt + 1)) { pbd = 0; pkt = int.Parse(cmbpkt.Text.Substring(0, 2)); } for (phut = pbd; phut <= pkt; phut = phut + 5) { if (gio.ToString().Length == 1) { w = "0" + gio.ToString(); } else { w = gio.ToString(); } if (phut.ToString().Length == 1) { q = "0" + phut.ToString(); } else { q = phut.ToString(); } a = w + ":" + q; //cmb.Items.Add(a); XmlWtr.WriteStartElement("Giolam"); XmlWtr.WriteElementString("Gio", a); XmlWtr.WriteEndElement(); } } XmlWtr.Flush(); XmlWtr.Close(); }
public static void writeGPX(string filename, List <CurrentState> flightdata) { System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter( Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".gpx", Encoding.ASCII); xw.WriteStartElement("gpx"); xw.WriteAttributeString("creator", MainV2.instance.Text); xw.WriteAttributeString("xmlns", "http://www.topografix.com/GPX/1/1"); xw.WriteStartElement("trk"); xw.WriteStartElement("trkseg"); foreach (CurrentState cs in flightdata) { xw.WriteStartElement("trkpt"); xw.WriteAttributeString("lat", cs.lat.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteAttributeString("lon", cs.lng.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("ele", cs.altasl.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("ele2", cs.alt.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("time", cs.datetime.ToString("yyyy-MM-ddTHH:mm:sszzzzzz")); xw.WriteElementString("course", (cs.yaw).ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("roll", cs.roll.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("pitch", cs.pitch.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("mode", cs.mode.ToString(new System.Globalization.CultureInfo("en-US"))); //xw.WriteElementString("speed", mod.model.Orientation.); //xw.WriteElementString("fix", cs.altitude); xw.WriteEndElement(); } xw.WriteEndElement(); xw.WriteEndElement(); int a = 0; DateTime lastsample = DateTime.MinValue; foreach (CurrentState cs in flightdata) { if (cs.datetime.Second != lastsample.Second) { lastsample = cs.datetime; } else { //continue; } xw.WriteStartElement("wpt"); xw.WriteAttributeString("lat", cs.lat.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteAttributeString("lon", cs.lng.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("name", (a++).ToString()); xw.WriteElementString("time", cs.datetime.ToString("yyyy-MM-ddTHH:mm:sszzzzzz")); xw.WriteElementString("ele", cs.altasl.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteEndElement(); //wpt } xw.WriteEndElement(); xw.Close(); }
private void WriteFile_Click(object sender, System.EventArgs e) { string XmlFile; System.IO.DirectoryInfo directoryInfo; System.IO.DirectoryInfo directoryXML; //Get the applications startup path directoryInfo = System.IO.Directory.GetParent(Application.StartupPath); //Set the output path if (directoryInfo.Name.ToString() == "bin") { directoryXML = System.IO.Directory.GetParent(directoryInfo.FullName); XmlFile = directoryXML.FullName + "\\" + OutputFileName.Text; } else { XmlFile = directoryInfo.FullName + "\\" + OutputFileName.Text; } //create the xml text writer object by providing the filename to write to //and the desired encoding. If the encoding is left null, then the writer //assumes UTF-8. XmlTextWriter XmlWtr = new System.Xml.XmlTextWriter(XmlFile, null); //set the formatting option of the xml file. The default indentation is 2 character spaces. //To change the default, use the Indentation property to set the number of IndentChars to use //and use the IndentChar property to set the character to use for indentation, such as the //tab character. Here the default is used. XmlWtr.Formatting = Formatting.Indented; //begin to write the xml document. This creates the xml declaration with the version attribute //set to "1.0". XmlWtr.WriteStartDocument(); //start the first element. XmlWtr.WriteStartElement("customers"); //create our first customer element. //this is a child element of the customers element. XmlWtr.WriteStartElement("customer"); //writes the entire element with the specified element name and //string value respectively. XmlWtr.WriteElementString("name", "Kevin Anders"); XmlWtr.WriteElementString("phone", "555.555.5555"); //end the customer element. XmlWtr.WriteEndElement(); //create another customer. XmlWtr.WriteStartElement("customer"); XmlWtr.WriteElementString("name", "Staci Richard"); XmlWtr.WriteElementString("phone", "555.122.1552"); //end the second customer element. XmlWtr.WriteEndElement(); //end the customers element. XmlWtr.WriteEndElement(); //now end the document. XmlWtr.WriteEndDocument(); //now flush the contents of the stream. XmlWtr.Flush(); //close the text writerj and write the xml file. XmlWtr.Close(); statusBar1.Text = "Output file has been written"; }
private void GeneraXML(System.Xml.XmlTextWriter writer) // As System.Xml.XmlTextWriter { try { writer.WriteStartDocument(); writer.WriteStartElement("FacturaElectronica"); writer.WriteAttributeString("xmlns", "https://tribunet.hacienda.go.cr/docs/esquemas/2017/v4.2/facturaElectronica"); writer.WriteAttributeString("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); writer.WriteAttributeString("xmlns:vc", "http://www.w3.org/2007/XMLSchema-versioning"); writer.WriteAttributeString("xmlns:xs", "http://www.w3.org/2001/XMLSchema"); // La clave se crea con la función CreaClave de la clase Datos writer.WriteElementString("Clave", _numeroClave); // 'El numero de secuencia es de 20 caracteres, // 'Se debe de crear con la función CreaNumeroSecuencia de la clase Datos writer.WriteElementString("NumeroConsecutivo", _numeroConsecutivo); // 'El formato de la fecha es yyyy-MM-ddTHH:mm:sszzz writer.WriteElementString("FechaEmision", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")); writer.WriteStartElement("Emisor"); writer.WriteElementString("Nombre", _emisor.Nombre); writer.WriteStartElement("Identificacion"); writer.WriteElementString("Tipo", _emisor.Identificacion_Tipo); writer.WriteElementString("Numero", _emisor.Identificacion_Numero); writer.WriteEndElement(); // 'Identificacion // '----------------------------------- // 'Los datos de las ubicaciones los puede tomar de las tablas de datos, // 'Debe ser exacto al que hacienda tiene registrado para su compañia writer.WriteStartElement("Ubicacion"); writer.WriteElementString("Provincia", _emisor.Ubicacion_Provincia); writer.WriteElementString("Canton", _emisor.Ubicacion_Canton); writer.WriteElementString("Distrito", _emisor.Ubicacion_Distrito); writer.WriteElementString("Barrio", _emisor.Ubicacion_Barrio); writer.WriteElementString("OtrasSenas", _emisor.Ubicacion_OtrasSenas); writer.WriteEndElement(); // 'Ubicacion writer.WriteStartElement("Telefono"); writer.WriteElementString("CodigoPais", _emisor.Telefono_CodigoPais); writer.WriteElementString("NumTelefono", _emisor.Telefono_Numero.ToString()); writer.WriteEndElement(); // 'Telefono writer.WriteElementString("CorreoElectronico", _emisor.CorreoElectronico); writer.WriteEndElement(); // Emisor // '------------------------------------ // 'Receptor es similar con emisor, los datos opcionales siempre siempre siempre omitirlos. // 'La ubicacion para el receptor es opcional por ejemplo writer.WriteStartElement("Receptor"); writer.WriteElementString("Nombre", _receptor.Nombre); writer.WriteStartElement("Identificacion"); // 'Los tipos de identificacion los puede ver en la tabla de datos writer.WriteElementString("Tipo", _receptor.Identificacion_Tipo); writer.WriteElementString("Numero", _receptor.Identificacion_Numero); writer.WriteEndElement(); // 'Identificacion writer.WriteStartElement("Telefono"); writer.WriteElementString("CodigoPais", _receptor.Telefono_CodigoPais); writer.WriteElementString("NumTelefono", _receptor.Telefono_Numero.ToString()); writer.WriteEndElement(); // 'Telefono writer.WriteElementString("CorreoElectronico", _receptor.CorreoElectronico); writer.WriteEndElement(); // Receptor // '------------------------------------ // 'Loa datos estan en la tabla correspondiente writer.WriteElementString("CondicionVenta", _condicionVenta); // '01: Contado // '02: Credito // '03: Consignación // '04: Apartado // '05: Arrendamiento con opcion de compra // '06: Arrendamiento con función financiera // '99: Otros // 'Este dato se muestra si la condicion venta es credito writer.WriteElementString("PlazoCredito", _plazoCredito); writer.WriteElementString("MedioPago", _medioPago); // '01: Efectivo // '02: Tarjeta // '03: Cheque // '04: Transferecia - deposito bancario // '05: Recaudado por terceros // '99: Otros writer.WriteStartElement("DetalleServicio"); // '------------------------------------- foreach (var xt in _dsDetalle) { writer.WriteStartElement("LineaDetalle"); writer.WriteElementString("NumeroLinea", xt.numeroDeLinea.ToString()); writer.WriteStartElement("Codigo"); writer.WriteElementString("Tipo", xt.tipoDeArticulo.ToString()); writer.WriteElementString("Codigo", xt.codigoArticulo.ToString()); writer.WriteEndElement(); // 'Codigo writer.WriteElementString("Cantidad", xt.cantidad.ToString()); // 'Para las unidades de medida ver la tabla correspondiente writer.WriteElementString("UnidadMedida", xt.unidadDeMedida.ToString()); writer.WriteElementString("Detalle", xt.detalle.ToString()); writer.WriteElementString("PrecioUnitario", String.Format("{0:N3}", xt.precioUnitario.ToString())); writer.WriteElementString("MontoTotal", String.Format("{0:N3}", xt.montoTotal.ToString())); writer.WriteElementString("MontoDescuento", String.Format("{0:N3}", xt.montoDescuento.ToString())); writer.WriteElementString("NaturalezaDescuento", xt.NaturalezaDescuento.ToString()); writer.WriteElementString("SubTotal", String.Format("{0:N3}", xt.subtotal.ToString())); writer.WriteStartElement("Impuesto"); writer.WriteElementString("Codigo", xt.codigoImpuesto.ToString()); writer.WriteElementString("Tarifa", xt.impuestoTarifa.ToString()); writer.WriteElementString("Monto", xt.impuestoMonto.ToString()); writer.WriteEndElement(); // Impuesto writer.WriteElementString("MontoTotalLinea", String.Format("{0:N3}", xt.montoTotalLinea.ToString())); writer.WriteEndElement(); // LineaDetalle } // '------------------------------------- writer.WriteEndElement(); // DetalleServicio writer.WriteStartElement("ResumenFactura"); // Estos campos son opcionales, solo fin desea facturar en dólares writer.WriteElementString("CodigoMoneda", _codigoMoneda); writer.WriteElementString("TipoCambio", "1.00000"); // ================= //SACAR CALCULOS PARA FACTURA double totalComprobante = 0; double montoTotalImpuesto = 0; foreach (var y in _dsDetalle) { montoTotalImpuesto = montoTotalImpuesto + y.impuestoMonto; } totalComprobante = 0 + montoTotalImpuesto; // 'En esta parte los totales se pueden ir sumando linea a linea cuando se carga el detalle // 'ó se pasa como parametros al inicio writer.WriteElementString("TotalServGravados", "0.00000"); writer.WriteElementString("TotalServExentos", "0.00000"); writer.WriteElementString("TotalMercanciasGravadas", "0.00000"); writer.WriteElementString("TotalMercanciasExentas", "0.00000"); writer.WriteElementString("TotalGravado", "0.00000"); writer.WriteElementString("TotalExento", "0.00000"); writer.WriteElementString("TotalVenta", "0.00000"); writer.WriteElementString("TotalDescuentos", "0.00000"); writer.WriteElementString("TotalVentaNeta", "0.00000"); writer.WriteElementString("TotalImpuesto", String.Format("{0:N3}", montoTotalImpuesto.ToString())); writer.WriteElementString("TotalComprobante", String.Format("{0:N3}", totalComprobante.ToString())); writer.WriteEndElement(); // ResumenFactura // 'Estos datos te los tiene que brindar los encargados del area financiera writer.WriteStartElement("Normativa"); writer.WriteElementString("NumeroResolucion", "DGT-R-48-2016"); writer.WriteElementString("FechaResolucion", "07-10-2016 01:00:00"); writer.WriteEndElement(); // Normativa // 'Aqui va la firma, despues la agregamos. writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); } catch (Exception ex) { throw ex; } }
public string CriarXmlRequisicao(string strMatricSistema, string usuarioSistema, string ipusuario, string usuariorede, string strAutenticacaoCriptografada = "", string strCaminhoCPR = "", string pSenha = "") { //Rotina que Gera a string de Requisição da Autenticação string strRetorno = ""; string strNomeArquivoXML = ""; XmlTextWriter xmlRequisicao = default(XmlTextWriter); XmlDocument docXML = default(XmlDocument); StreamReader SR = default(StreamReader); try { if (!System.IO.Directory.Exists(ConfigurationSettings.AppSettings["CaminhoXML"].ToString() + "\\XML\\")) { System.IO.Directory.CreateDirectory(ConfigurationSettings.AppSettings["CaminhoXML"].ToString() + "\\XML\\"); } //Procura por um nome de arquivo que ainda não exista //strNomeArquivoXML = AppDomain.CurrentDomain.BaseDirectory + "\\XML\\XML_REQ_AUT_" + String.Format(DateTime.Now, "ddMMyyyyhhmmss") + ".xml"; strNomeArquivoXML = ConfigurationSettings.AppSettings["CaminhoXML"].ToString() + "\\XML\\XML_REQ_AUT_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml"; while (System.IO.File.Exists(strNomeArquivoXML)) { strNomeArquivoXML = AppDomain.CurrentDomain.BaseDirectory + "\\XML\\XML_REQ_AUT_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml"; } xmlRequisicao = new System.Xml.XmlTextWriter(strNomeArquivoXML, System.Text.Encoding.UTF8); //INÍCIO DO DOCUMENTO XML xmlRequisicao.WriteStartDocument(); //INÍCIO DA TAG 'REQUISICAO' xmlRequisicao.WriteStartElement("requisicao"); xmlRequisicao.WriteAttributeString("xmlns", "http://ntconsult.com.br/webservices/"); xmlRequisicao.WriteAttributeString("versao", "0.10"); //Caso a Autenticação seja criptografia RSA então este elemento deverá ser criado: AutenticacaoCriptografada //Caso o parâmetro tenha sido informado e não esteja em branco efetua a autenticação através de RSA if ((strAutenticacaoCriptografada != null)) { if (!string.IsNullOrEmpty(strAutenticacaoCriptografada.Trim())) { xmlRequisicao.WriteElementString("AutenticacaoCriptografada", strAutenticacaoCriptografada); } } else { xmlRequisicao.WriteElementString("usr", usuarioSistema); xmlRequisicao.WriteElementString("senha", pSenha); } xmlRequisicao.WriteElementString("matricsistema", strMatricSistema); xmlRequisicao.WriteElementString("usuariorede", usuariorede); xmlRequisicao.WriteElementString("ipusuario", ipusuario); //FIM DA TAG 'REQUISICAO' xmlRequisicao.WriteEndElement(); //FIM DO DOCUMENTO XML xmlRequisicao.WriteEndDocument(); xmlRequisicao.Flush(); xmlRequisicao.Close(); docXML = new XmlDocument(); docXML.PreserveWhitespace = false; SR = File.OpenText(strNomeArquivoXML); docXML.LoadXml(SR.ReadToEnd()); SR.Close(); strRetorno = docXML.InnerXml.ToString(); //apos usar o arquivo, apaga-lo File.Delete(strNomeArquivoXML); return(strRetorno); } catch (Exception ex) { throw ex; } }