WriteEndDocument() public method

public WriteEndDocument ( ) : void
return void
Example #1
1
        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;
            }
        }
Example #2
1
        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();
            }
        }
Example #4
1
        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.");
        }
Example #5
0
        private void button_OK_Click(object sender, EventArgs e)
        {
            if (!Desc.Convex)
              MessageBox.Show("Útvar není konvexní a při detekci kolizí bude nahrazen jeho konvexním obalem.","Konvexnost",MessageBoxButtons.OK,MessageBoxIcon.Information);

            using (XmlTextWriter Object = new XmlTextWriter("objects\\" + text_objName.Text + ".xml", Encoding.UTF8))
            {
                Object.WriteStartDocument();
                Object.WriteStartElement("Geometry");
                Object.WriteAttributeString("W", Desc.Width.ToString());
                Object.WriteAttributeString("H", Desc.Height.ToString());
                Object.WriteAttributeString("D", text_objDepth.Text);
                Object.WriteAttributeString("C", text_objDrag.Text);
                Object.WriteAttributeString("Color", col);
                Object.WriteAttributeString("Tension", text_objTension.Text);
                Object.WriteAttributeString("ID", System.Guid.NewGuid().ToString());

                Object.WriteStartElement("COG");
                Object.WriteAttributeString("X", (COG.Value.X-Desc.Centroid.X).ToString());
                Object.WriteAttributeString("Y", (COG.Value.Y-Desc.Centroid.Y).ToString());
                Object.WriteEndElement();

                for (int i = 0; i < pts.Count; i++)
                {
                    Object.WriteStartElement("Vertex");
                    Object.WriteAttributeString("X", (((PointF)pts[i]).X - Desc.Centroid.X).ToString());
                    Object.WriteAttributeString("Y", (((PointF)pts[i]).Y - Desc.Centroid.Y).ToString());
                    Object.WriteEndElement();
                }

                Object.WriteEndElement();
                Object.WriteEndDocument();
            }
            Close();
        }
Example #6
0
        static void Main(string[] args)
        {
            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 name = string.Empty;
                using (XmlReader reader = XmlReader.Create("../../../MusicCatalogue.xml"))
                {
                    while (reader.Read())
                    {
                        if ((reader.NodeType == XmlNodeType.Element) &&
                            (reader.Name == "name"))
                        {
                            name = reader.ReadElementString();
                        }
                        else if ((reader.NodeType == XmlNodeType.Element) &&
                            (reader.Name == "artist"))
                        {
                            string artist = reader.ReadElementString();
                            WriteAlbum(writer, name, artist);
                        }
                    }
                }
                writer.WriteEndDocument();
                Console.WriteLine("Document album.xml was created.");
            }
        }
        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.");
        }
Example #8
0
        /// <summary>
        ///   Converts the memory hash table to XML
        /// </summary>
        public void Dump2Xml()
        {
            if ( ( TheHT.Count > 0 ) && IsDirty )
            {
                XmlTextWriter writer = new
                          XmlTextWriter( string.Format( "{0}", Filename ), null );

                writer.WriteStartDocument();
                writer.WriteComment( "Comments: " + Name );
                writer.WriteStartElement( "media-list" );

                IDictionaryEnumerator myEnumerator = TheHT.GetEnumerator();
                while ( myEnumerator.MoveNext() )
                {
                    MediaItem m = (MediaItem) myEnumerator.Value;
                    WriteMediaNode( writer, m );
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
                Utility.Announce( string.Format( "{0} created.",  Filename ) );
            }
            else
                Utility.Announce( string.Format( "No changes to {0}.", Filename ) );
        }
        static void Main()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            XmlDocument queryDocument = new XmlDocument();
            queryDocument.Load("../../reviews-queries.xml");
            using (XmlTextWriter writer = new XmlTextWriter("../../reviews-search-results.xml", Encoding.UTF8))
            {
                InitializeWriter(writer);

                writer.WriteStartDocument();
                writer.WriteStartElement("search-results");

                ReviewsDAO reviewsDao = new ReviewsDAO();

                using (LogsContext logsContext = new LogsContext())
                {
                    XmlNodeList queryNodes = queryDocument.SelectNodes("/review-queries/query");
                    foreach (XmlNode queryNode in queryNodes)
                    {
                        LogQuery(logsContext, queryNode.OuterXml);

                        WriteResultSet(writer, reviewsDao, queryNode);
                    }

                    writer.WriteEndDocument();
                }
            }

            Console.WriteLine("Done! See the file in project's directory.");
        }
Example #10
0
        public void Create( string path )
        {
            XmlTextWriter xml;

            if( path == "" )
            {
                return;
            }

            m_fileName = path;

            if( File.Exists( m_fileName ) == false )
            {
                xml = new XmlTextWriter( m_fileName, System.Text.Encoding.UTF8 );

                xml.Formatting = System.Xml.Formatting.Indented;

                xml.WriteStartDocument();

                xml.WriteStartElement( "mdna" );
                xml.WriteEndElement();

                xml.WriteEndDocument();

                xml.Close();
            }
        }
Example #11
0
        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();
            }
        }
Example #12
0
        /// <summary>
        /// Write a log into the xml file
        /// </summary>
        /// <param name="log"></param>
        public void writeLog(string log)
        {
            string xmlName = "record.xml";
            if (!System.IO.File.Exists(xmlName))
            {
                XmlTextWriter writer = new XmlTextWriter(xmlName, System.Text.Encoding.UTF8);
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2;

                writer.WriteStartElement("Record");
                writer.WriteEndElement();

                writer.WriteEndDocument();//End
                writer.Close();
            }
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlName);
            XmlElement root = doc.DocumentElement;
            XmlElement elementRecord = doc.CreateElement("record");
            XmlElement elementTime = doc.CreateElement("time");
            XmlElement elementEvent = doc.CreateElement("event");
            XmlText time = doc.CreateTextNode(getSystemTime());
            XmlText myevent = doc.CreateTextNode(log);
            elementRecord.AppendChild(elementTime);
            elementRecord.AppendChild(elementEvent);
            elementTime.AppendChild(time);
            elementEvent.AppendChild(myevent);
            root.InsertAfter(elementRecord, root.LastChild);
            doc.Save(xmlName);
        }
Example #13
0
        private void WriteFeed(IEnumerable<DonaldEpisode> episodes, Stream responseStream, string url)
        {
            XmlTextWriter objX = new XmlTextWriter(responseStream, Encoding.UTF8);
            objX.WriteStartDocument();
            objX.WriteStartElement("rss");
            objX.WriteAttributeString("version", "2.0");
            objX.WriteStartElement("channel");
            objX.WriteElementString("title", "Donald Inc.");
            objX.WriteElementString("link", url);
            objX.WriteElementString("description",
                                    "Your custom donald feed!");
            objX.WriteElementString("copyright", "(c) 2011, Chuck Norris.");
            objX.WriteElementString("ttl", "5");
            foreach (var episode in episodes)
            {
                objX.WriteStartElement("item");
                objX.WriteElementString("title", episode.Title);
                objX.WriteElementString("description", episode.Content);
                objX.WriteElementString("link",
                                        Configuration.ApiUri + "/" + episode.Id);
                objX.WriteElementString("pubDate", episode.ReleaseDate.Value.ToString("R"));
                objX.WriteStartElement("enclosure");
                objX.WriteAttributeString("url", Configuration.ApiUri + "/" + episode.Id + "/jpg");
                objX.WriteAttributeString("type", "application/jpg");
                objX.WriteEndElement();
                objX.WriteEndElement();
            }

            objX.WriteEndElement();
            objX.WriteEndElement();
            objX.WriteEndDocument();
            objX.Flush();
        }
Example #14
0
        public void XMLCheck()
        {
            try
            {
                if (!File.Exists(SettingsFile))
                {
                    xwriter = new XmlTextWriter(SettingsFile, null);
                    xwriter.Formatting = Formatting.Indented;
                    xwriter.WriteStartDocument();
                    xwriter.WriteStartElement("settings");
                    xwriter.WriteStartElement("twitch_server");
                    xwriter.WriteAttributeString("value", null);
                    xwriter.WriteEndElement();
                    xwriter.WriteStartElement("twitch_name");
                    xwriter.WriteAttributeString("value", null);
                    xwriter.WriteEndElement();
                    xwriter.WriteStartElement("twitch_auth");
                    xwriter.WriteAttributeString("value", null);
                    xwriter.WriteEndElement();
                    xwriter.WriteEndDocument();
                    xwriter.Close();
                }
            }

            catch (Exception ex)
            {

            }
            finally
            {
                //Nothing yet
            }
        }
Example #15
0
        /// <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());
            }
        }
Example #16
0
        public void ChartToXmlText() {
            var cosmetic = new CosmeticAttribute
                           {
                               BgSWF = "~/FusionCharts/BgChart.swf",
                               BgSWFAlpha = 100,
                               CanvasBackgroundAttr = new BackgroundAttribute() { BgColor = Color.Red, BgRatio = "12,12" }
                           };

            var sb = new StringBuilder();

            using(var writer = new XmlTextWriter(new StringWriter(sb))) {
                writer.WriteStartDocument(true);

                writer.WriteStartElement("chart");

#pragma warning disable 0618

                cosmetic.WriteChartAttribute(writer);
                // GenerateXmlAttributes(cosmetic, writer);

#pragma warning restore 0618

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }

            Console.WriteLine(sb.ToString());
        }
Example #17
0
        private static void Main()
        {
            helper.ConsoleMio.Setup();
            helper.ConsoleMio.PrintHeading("Traverse Folders");

            helper.ConsoleMio.PrintColorText("Select a directory to traverse\n", ConsoleColor.Red);

            string directoryPath = helper.GetDirectory();

            string savePath = helper.SelectSaveLocation("XML file|*.xml");

            using(var writeStream = new XmlTextWriter(savePath, Encoding.UTF8))
            {
                var dirInfo = new DirectoryInfo(directoryPath);

                writeStream.Formatting = Formatting.Indented;
                writeStream.WriteStartDocument();
                writeStream.WriteStartElement("Directories");

                var traversR = new TraverseUsingXmlWriter(writeStream);

                traversR.TraverseFolder(dirInfo);

                writeStream.WriteEndDocument();
            }

            helper.ConsoleMio.PrintColorText("Completed\n ", ConsoleColor.Green);

            helper.ConsoleMio.Restart(Main);
        }
Example #18
0
        public XmlHelper(string filename)
        {
            if (filename == string.Empty)
                throw new ArgumentNullException(filename);

            _filename = filename;

            var path = Path.GetDirectoryName(filename) ;

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            if(!File.Exists(filename))
            {
                var writer = new XmlTextWriter(filename,System.Text.Encoding.UTF8);
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2;
                writer.WriteStartElement("categories");
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
            }
            _xml = XDocument.Load(_filename);
        }
        /// <summary>
        /// Export a MacGui style plist preset.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="preset">
        /// The preset.
        /// </param>
        /// <param name="build">
        /// The build.PictureModulusPictureModulus
        /// </param>
        public static void Export(string path, Preset preset, string build)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            EncodeTask parsed = new EncodeTask(preset.Task);
            using (XmlTextWriter xmlWriter = new XmlTextWriter(path, Encoding.UTF8) { Formatting = Formatting.Indented })
            {
                // Header
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteDocType(
                    "plist", "-//Apple//DTD PLIST 1.0//EN", @"http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);

                xmlWriter.WriteStartElement("plist");
                xmlWriter.WriteStartElement("array");

                // Add New Preset Here. Can write multiple presets here if required in future.
                WritePreset(xmlWriter, parsed, preset, build);

                // Footer
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();

                xmlWriter.WriteEndDocument();

                // Closeout
                xmlWriter.Close();
            }
        }
        public static void Main()
        {
            XmlTextWriter writer = new XmlTextWriter("../../albums.xml", Encoding.UTF8);
            using (writer)
            {
                writer.WriteStartDocument();
                writer.Formatting = Formatting.Indented;
                writer.IndentChar = '\t';
                writer.Indentation = 1;
                writer.WriteStartElement("albums");

                string name = string.Empty;
                using (XmlReader reader = XmlReader.Create("../../catalog.xml"))
                {
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element && reader.Name == "name")
                        {
                            name = reader.ReadElementString();
                        }
                        else if (reader.NodeType == XmlNodeType.Element &&reader.Name == "artist")
                        {
                            string artist = reader.ReadElementString();
                            WriteAlbum(writer, name, artist);
                        }
                    }
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
            } 
        }
Example #21
0
        /// -----------------------------------------------------------------------------
        /// <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;
        }
Example #22
0
        public void saveSettingsButton_Click(object sender, EventArgs e)
        {
            Form1 parent = (Form1)Application.OpenForms["Form1"];
            FileStream fs = new FileStream("artsin_launcher.cfg", FileMode.Create);
            XmlTextWriter writer = new XmlTextWriter(fs, Encoding.Unicode);
            writer.Formatting = Formatting.Indented;

            writer.WriteStartDocument();
            writer.WriteStartElement("ArtSinLauncherCfg");
            writer.WriteAttributeString("version", "1.1");

            writer.WriteStartElement("Memory");
            writer.WriteAttributeString("minMemory", ((int)minMemNumericUpDown.Value).ToString());
            writer.WriteAttributeString("maxMemory", ((int)maxMemNumericUpDown.Value).ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("SaveSettings");
            writer.WriteAttributeString("isTrue", saveSettingsCheckBox.Checked.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("Login");
            writer.WriteAttributeString("value", parent.loginTextBox.Text);
            writer.WriteEndElement();

            writer.WriteStartElement("License");
            writer.WriteAttributeString("isTrue", parent.licenseCheckBox.Checked.ToString());
            writer.WriteEndElement();

            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Close();
            fs.Close();
        }
Example #23
0
        /// <summary>
        /// Export a MacGui style plist preset.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="preset">
        /// The preset.
        /// </param>
        public static void Export(string path, Preset preset)
        {
            EncodeTask parsed = QueryParserUtility.Parse(preset.Query);
            XmlTextWriter xmlWriter = new XmlTextWriter(path, Encoding.UTF8) { Formatting = Formatting.Indented };

            // Header
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteDocType("plist", "-//Apple//DTD PLIST 1.0//EN",
                                @"http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);

            xmlWriter.WriteStartElement("plist");
            xmlWriter.WriteStartElement("array");

            // Add New Preset Here. Can write multiple presets here if required in future.
            WritePreset(xmlWriter, parsed, preset);

            // Footer
            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndElement();

            xmlWriter.WriteEndDocument();

            // Closeout
            xmlWriter.Close();
        }
Example #24
0
        static void Main()
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string line = reader.ReadLine();

                if (line == null)
                {
                    Console.WriteLine("The text file is empty");
                    return;
                }

                using (XmlTextWriter writer = new XmlTextWriter(xmlFilePath, encoding))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.IndentChar = '\t';
                    writer.Indentation = 1;

                    writer.WriteStartDocument();
                    writer.WriteStartElement("People");
                    writer.WriteAttributeString("name", "People's List");

                    while (line != null)
                    {
                        WritePerson(line, writer);
                        line = reader.ReadLine();
                    }

                    writer.WriteEndDocument();
                }
            }
        }
Example #25
0
        public void CreateXml()
        {
            if ( ( m_SeasonList.Count > 0 ) )
            {
                const string fileName = "NFL.xml";
                XmlTextWriter writer = new
                    XmlTextWriter(string.Format("{0}{1}", Utility.OutputDirectory() + "xml\\", fileName), null);
                writer.Formatting = Formatting.Indented;

                writer.WriteStartDocument();
                writer.WriteComment( "Comments: NFL Season List" );
                writer.WriteStartElement( "nfl" );
                writer.WriteStartElement("season-list");

                foreach ( NflSeason s in m_SeasonList )
                {
                    WriteSeasonNode( writer, s );
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
                RosterLib.Utility.Announce( fileName + " created" );
            }
        }
        /// <summary>
        /// The traverse directory.
        /// </summary>
        /// <param name="directory">
        /// The directory.
        /// </param>
        public static void TraverseDirectory(string directory)
        {
            // Write a program to traverse given directory and write to a XML file its contents together with all subdirectories and files.
            var dir = new DirectoryInfo(directory);

            using (writer = new XmlTextWriter(xmlDirFilename, Encoding.UTF8))
            {
                writer.Formatting = Formatting.Indented;
                writer.IndentChar = '\t';
                writer.Indentation = 1;

                writer.WriteStartDocument();
                writer.WriteStartElement("dirStructure");

                foreach (var file in dir.GetFiles())
                {
                    writer.WriteStartElement("file");
                    writer.WriteAttributeString("name", file.Name);
                    writer.WriteEndElement();
                }

                foreach (var subDir in dir.GetDirectories())
                {
                    CreateSubdirectoryXml(subDir);
                }

                writer.WriteEndDocument();
            }
        }
Example #27
0
        public override bool Execute()
        {
            // Delete the file if it exists.
            if (File.Exists(Output))
            {
                File.Delete(Output);
            }

            using (var stream = File.Create(Output))
            using (var xmlWriter = new XmlTextWriter(stream, Encoding.UTF8))
            using (var parser = new PoParser(new StreamReader(Input)).Parse())
            {
                xmlWriter.Formatting = Formatting.Indented;
                xmlWriter.IndentChar = ' ';
                xmlWriter.Indentation = 4;
                // Root.
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("WixLocalization", "http://schemas.microsoft.com/wix/2006/localization");
                foreach (var message in parser.Messages)
                {
                    if(message.IsHeader)
                        xmlWriter.WriteAttributeString("Culture", parser.Header?.Language?.Name ?? "en-us");

                    var entry = message as PoEntry;
                    if (entry != null) AddEntry(xmlWriter, entry); //We only treat simple message for now
                }
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();
            }

            return true;
        }
Example #28
0
        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();
        }
Example #29
0
        public void escribirXMl(string nombreF, List<Contacto> contactos)
        {
            FileStream fichero = new FileStream(nombreF, FileMode.Create, FileAccess.Write);
            //crearXml(nombreF);
            XmlTextWriter escritorXml = new XmlTextWriter(fichero, Encoding.Default);
            escritorXml.Formatting = Formatting.Indented;
            escritorXml.WriteStartDocument();
            escritorXml.WriteStartElement("Agenda");
            foreach (Contacto c in contactos)
            {
                escritorXml.WriteStartElement("Contacto");
                escritorXml.WriteStartElement("nombre", c.nombre);
                escritorXml.WriteEndElement();
                escritorXml.WriteStartElement("apellido", c.apellido);
                escritorXml.WriteEndElement();
                escritorXml.WriteStartElement("direccion", c.direccion);
                escritorXml.WriteEndElement();
                escritorXml.WriteStartElement("telefonos");
                escritorXml.WriteStartElement("telcasa", c.tlfCasa);
                escritorXml.WriteEndElement();
                escritorXml.WriteStartElement("telmovil", c.tlfMovil);
                escritorXml.WriteEndElement();
                escritorXml.WriteStartElement("teltrabajo", c.tlfTrabajo);
                escritorXml.WriteEndElement();
                escritorXml.WriteEndElement();
                escritorXml.WriteEndElement();
            }

            escritorXml.WriteEndElement();
            escritorXml.WriteEndDocument();
            escritorXml.Close();
        }
Example #30
0
 public static void SaveAsXml(IEnumerable<Chapter> chapters, string path)
 {
     var writer = new XmlTextWriter(path, Encoding.GetEncoding("ISO-8859-1"));
     writer.Formatting = Formatting.Indented;
     writer.WriteStartDocument();
         writer.WriteDocType("Chapters", null, "matroskachapters.dtd", null);
         writer.WriteStartElement("Chapters");
             writer.WriteStartElement("EditionEntry");
             foreach (var chapter in chapters.Where(chapter => chapter.Keep))
             {
                 writer.WriteStartElement("ChapterAtom");
                     writer.WriteStartElement("ChapterTimeStart");
                         writer.WriteString(chapter.StartTimeXmlFormat); // 00:00:00.000
                     writer.WriteEndElement();
                     writer.WriteStartElement("ChapterDisplay");
                         writer.WriteStartElement("ChapterString");
                             writer.WriteString(chapter.Title); // Chapter 1
                         writer.WriteEndElement();
                         if (chapter.Language != null && chapter.Language != Language.Undetermined)
                         {
                             writer.WriteStartElement("ChapterLanguage");
                                 writer.WriteString(chapter.Language.ISO_639_2); // eng
                             writer.WriteEndElement();
                         }
                     writer.WriteEndElement();
                 writer.WriteEndElement();
             }
             writer.WriteEndElement();
         writer.WriteEndElement();
     writer.WriteEndDocument();
     writer.Close();
 }
Example #31
0
        ///<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();
        }
Example #32
0
            public void SaveResources()
            {
                using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Controller.ResourcesFile, Encoding.UTF8))
                {
                    writer.Formatting = System.Xml.Formatting.Indented;
                    writer.WriteStartDocument();
                    writer.WriteStartElement("resources");

                    foreach (Resource resource in _resourceList.Values)
                    {
                        if (resource != Root)
                        {
                            resource.WriteXML(writer);
                        }
                    }

                    writer.WriteEndElement();
                    writer.WriteEndDocument();

                    writer.Flush();
                    writer.Close();
                }
            }
        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;
            }
        }
Example #34
0
        /// <summary>
        /// 将DataTable的内容写入到XML文件中
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="address">XML文件地址</param>
        public static bool DBWriteToXml(System.Data.DataTable dt, string address)
        {
            try
            {
                //如果文件DataTable.xml存在则直接删除
                if (System.IO.File.Exists(address))
                {
                    System.IO.File.Delete(address);
                }

                System.Xml.XmlTextWriter writer =
                    new System.Xml.XmlTextWriter(address, Encoding.GetEncoding("GBK"));
                writer.Formatting = System.Xml.Formatting.Indented;

                //XML文档创建开始
                writer.WriteStartDocument();

                writer.WriteComment("DataTable: " + dt.TableName);

                writer.WriteStartElement("DataTable"); //DataTable开始

                writer.WriteAttributeString("TableName", dt.TableName);
                writer.WriteAttributeString("CountOfRows", dt.Rows.Count.ToString());
                writer.WriteAttributeString("CountOfColumns", dt.Columns.Count.ToString());

                writer.WriteStartElement("ClomunName", ""); //ColumnName开始

                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    writer.WriteAttributeString(
                        "Column" + i.ToString(), dt.Columns[i].ColumnName);
                }

                writer.WriteEndElement(); //ColumnName结束

                //按行各行
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    writer.WriteStartElement("Row" + j.ToString(), "");

                    //打印各列
                    for (int k = 0; k < dt.Columns.Count; k++)
                    {
                        writer.WriteAttributeString(
                            "Column" + k.ToString(), dt.Rows[j][k].ToString());
                    }

                    writer.WriteEndElement();
                }

                writer.WriteEndElement(); //DataTable结束

                writer.WriteEndDocument();
                writer.Close();

                //XML文档创建结束
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }

            return(true);
        }
        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;
            }
        }
Example #36
0
        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";
        }
        /// <summary> Writes the mapping of all mapped classes of the specified assembly in the specified stream. </summary>
        /// <param name="stream">Where the xml is written.</param>
        /// <param name="assembly">Assembly used to extract user-defined types containing a valid attribute (can be [Class] or [xSubclass]).</param>
        public virtual void Serialize(System.IO.Stream stream, System.Reflection.Assembly assembly)
        {
            if (stream == null)
            {
                throw new System.ArgumentNullException("stream");
            }
            if (assembly == null)
            {
                throw new System.ArgumentNullException("assembly");
            }

            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);
            writer.Formatting = System.Xml.Formatting.Indented;
            writer.WriteStartDocument();
            if (WriteDateComment)
            {
                writer.WriteComment(string.Format("Generated from NHibernate.Mapping.Attributes on {0}.", System.DateTime.Now.ToString("u")));
            }
            WriteHibernateMapping(writer, null);

            // Write imports (classes decorated with the [ImportAttribute])
            foreach (System.Type type in assembly.GetTypes())
            {
                object[] imports = type.GetCustomAttributes(typeof(ImportAttribute), false);
                foreach (ImportAttribute import in imports)
                {
                    writer.WriteStartElement("import");
                    if (import.Class != null && import.Class != string.Empty)
                    {
                        writer.WriteAttributeString("class", import.Class);
                    }
                    else                     // Assume that it is the current type that must be imported
                    {
                        writer.WriteAttributeString("class", HbmWriterHelper.GetNameWithAssembly(type));
                    }
                    if (import.Rename != null && import.Rename != string.Empty)
                    {
                        writer.WriteAttributeString("rename", import.Rename);
                    }
                    writer.WriteEndElement();
                }
            }

            // Write classes and x-subclasses (classes must come first if inherited by "external" subclasses)
            int classCount = 0;

            System.Collections.ArrayList mappedClassesNames = new System.Collections.ArrayList();
            foreach (System.Type type in assembly.GetTypes())
            {
                if (!IsClass(type))
                {
                    continue;
                }
                HbmWriter.WriteClass(writer, type);
                mappedClassesNames.Add(HbmWriterHelper.GetNameWithAssembly(type));
                classCount++;
            }

            System.Collections.ArrayList subclasses = new System.Collections.ArrayList();
            System.Collections.Specialized.StringCollection extendedClassesNames = new System.Collections.Specialized.StringCollection();
            foreach (System.Type type in assembly.GetTypes())
            {
                if (!IsSubclass(type))
                {
                    continue;
                }
                bool        map = true;
                System.Type t   = type;
                while ((t = t.DeclaringType) != null)
                {
                    if (IsClass(t) || AreSameSubclass(type, t)) // If a base class is also mapped... (Note: A x-subclass can only contain x-subclasses of the same family)
                    {
                        map = false;                            // This class's mapping is already included in the mapping of the base class
                        break;
                    }
                }
                if (map)
                {
                    subclasses.Add(type);
                    if (IsSubclass(type, typeof(SubclassAttribute)))
                    {
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(SubclassAttribute), false)[0] as SubclassAttribute).Extends);
                    }
                    else if (IsSubclass(type, typeof(JoinedSubclassAttribute)))
                    {
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(JoinedSubclassAttribute), false)[0] as JoinedSubclassAttribute).Extends);
                    }
                    else if (IsSubclass(type, typeof(UnionSubclassAttribute)))
                    {
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(UnionSubclassAttribute), false)[0] as UnionSubclassAttribute).Extends);
                    }
                }
            }
            classCount += subclasses.Count;
            MapSubclasses(subclasses, extendedClassesNames, mappedClassesNames, writer);

            writer.WriteEndElement();             // </hibernate-mapping>
            writer.WriteEndDocument();
            writer.Flush();

            if (classCount == 0)
            {
                throw new MappingException("The following assembly contains no mapped classes: " + assembly.FullName);
            }
            if (!Validate)
            {
                return;
            }

            // Validate the generated XML stream
            try
            {
                writer.BaseStream.Position = 0;
                System.Xml.XmlTextReader tr = new System.Xml.XmlTextReader(writer.BaseStream);

                var reader = CreateReader(tr);

                _stop = false;
                while (reader.Read() && !_stop)                // Read to validate (stop at the first error)
                {
                    ;
                }
            }
            catch (System.Exception ex)
            {
                Error.Append(ex.ToString()).Append(System.Environment.NewLine + System.Environment.NewLine);
            }
        }
Example #38
0
        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;
            }
        }