WriteStartDocument() public method

public WriteStartDocument ( ) : void
return void
Example #1
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();
            }
        }
Example #2
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 #3
1
        private void CreateConfig()
        {
            this.ConfigFileLocation = Path.Combine(this.ThemeDirectory, "Theme.config");

            using (var xml = new XmlTextWriter(this.ConfigFileLocation, Encoding.UTF8))
            {
                xml.WriteStartDocument(true);
                xml.Formatting = Formatting.Indented;
                xml.Indentation = 4;

                xml.WriteStartElement("configuration");
                xml.WriteStartElement("appSettings");

                this.AddKey(xml, "ThemeName", this.Info.ThemeName);
                this.AddKey(xml, "Author", this.Info.Author);
                this.AddKey(xml, "AuthorUrl", this.Info.AuthorUrl);
                this.AddKey(xml, "AuthorEmail", this.Info.AuthorEmail);
                this.AddKey(xml, "ConvertedBy", this.Info.ConvertedBy);
                this.AddKey(xml, "ReleasedOn", this.Info.ReleasedOn);
                this.AddKey(xml, "Version", this.Info.Version);
                this.AddKey(xml, "Category", this.Info.Category);
                this.AddKey(xml, "Responsive", this.Info.Responsive ? "Yes" : "No");
                this.AddKey(xml, "Framework", this.Info.Framework);
                this.AddKey(xml, "Tags", string.Join(",", this.Info.Tags));
                this.AddKey(xml, "HomepageLayout", this.Info.HomepageLayout);
                this.AddKey(xml, "DefaultLayout", this.Info.DefaultLayout);

                xml.WriteEndElement(); //appSettings
                xml.WriteEndElement(); //configuration
                xml.Close();
            }
        }
Example #4
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;
            }
        }
        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 #6
1
 // XmlWriterSample1/form.cs
 private void button1_Click(object sender, System.EventArgs e)
 {
     // change to match you path structure
     string fileName="booknew.xml";
     //create the XmlTextWriter
     XmlTextWriter tw=new XmlTextWriter(fileName,null);
     //set the formatting to indented
     tw.Formatting=Formatting.Indented;
     tw.WriteStartDocument();
     //Start creating elements and attributes
     tw.WriteStartElement("book");
     tw.WriteAttributeString("genre","Mystery");
     tw.WriteAttributeString("publicationdate","2001");
     tw.WriteAttributeString("ISBN","123456789");
     tw.WriteElementString("title","Case of the Missing Cookie");
     tw.WriteStartElement("author");
     tw.WriteElementString("name","Cookie Monster");
     tw.WriteEndElement();
     tw.WriteElementString("price","9.99");
     tw.WriteEndElement();
     tw.WriteEndDocument();
     //clean up
     tw.Flush();
     tw.Close();
 }
Example #7
0
		/// <summary>
		/// Initializes the writer to write redirected output. 
		/// </summary>              
		/// <remarks>Depending on the <c>method</c> attribute value, 
		/// <c>XmlTextWriter</c> or <c>StreamWriter</c> is created. 
		/// <c>XmlTextWriter</c> is used for outputting XML and  
		/// <c>StreamWriter</c> - for plain text.
		/// </remarks>
		public void InitWriter(XmlResolver outResolver)
		{
			if (outResolver == null)
			{
				outResolver = new OutputResolver(Directory.GetCurrentDirectory());
			}
			// Save current directory
			//storedDir = Directory.GetCurrentDirectory();
			string outFile = outResolver.ResolveUri(null, href).LocalPath;
			DirectoryInfo dir = Directory.GetParent(outFile);
			if (!dir.Exists)
				dir.Create();
			// Create writer
			if (method == OutputMethod.Xml)
			{
				xmlWriter = new XmlTextWriter(outFile, encoding);
				if (indent)
					xmlWriter.Formatting = Formatting.Indented;
				if (!omitXmlDecl)
				{
					if (standalone)
						xmlWriter.WriteStartDocument(true);
					else
						xmlWriter.WriteStartDocument();
				}
			}
			else
				textWriter = new StreamWriter(outFile, false, encoding);
			// Set new current directory            
			//Directory.SetCurrentDirectory(dir.ToString());                                    
            href = ""; // clean the href for the next usage
		}
Example #8
0
 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; }
 }
Example #9
0
        public bool create(string xmlRoot, string fileName)
        {
            //create the root elements of the xml document if the dont alreasy exist
            try
            {
                if (!System.IO.File.Exists(fileName))
                {
                    XmlTextWriter xtw;
                    xtw = new XmlTextWriter(fileName, Encoding.UTF8);
                    xtw.WriteStartDocument();
                    xtw.WriteStartElement(xmlRoot);
                    xtw.WriteEndElement();
                    xtw.Close();

                    //if file exists return true
                    return true;
                }
                else { return false; }
            }
            catch (Exception err)
            {
                debugTerminal terminal = new debugTerminal();
                terminal.output(err.ToString());
                return false;
            }
        }
Example #10
0
        /// <summary>Serialize the <c>XmlRpcResponse</c> to the output stream.</summary>
        /// <param name="output">An <c>XmlTextWriter</c> stream to write data to.</param>
        /// <param name="obj">An <c>Object</c> to serialize.</param>
        /// <seealso cref="XmlRpcResponse"/>
        public override void Serialize(XmlTextWriter output, Object obj)
        {
            XmlRpcResponse response = (XmlRpcResponse) obj;

            output.WriteStartDocument();
            output.WriteStartElement(METHOD_RESPONSE);

            if (response.IsFault)
              output.WriteStartElement(FAULT);
            else
              {
            output.WriteStartElement(PARAMS);
            output.WriteStartElement(PARAM);
              }

            output.WriteStartElement(VALUE);

            SerializeObject(output,response.Value);

            output.WriteEndElement();

            output.WriteEndElement();
            if (!response.IsFault)
              output.WriteEndElement();
            output.WriteEndElement();
        }
        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();
        }
        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 #13
0
        private static void SaveXMLDictionarySettings <T>(XmlSerializableDictionary <string, T> Dic, String FilePath)
        {
            try
            {
                var tmpFile = FilePath + ".tmp";
                lock (Dic)
                {
                    using (System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(tmpFile, Encoding.UTF8))
                    {
                        xtw.Formatting = Formatting.Indented;
                        xtw.WriteStartDocument();
                        xtw.WriteStartElement("dictionary");

                        Dic.WriteXml(xtw);
                        xtw.WriteEndElement();
                    }
                    if (File.Exists(FilePath))
                    {
                        File.Replace(tmpFile, FilePath, FilePath + ".backup", true);
                    }
                    else
                    {
                        File.Move(tmpFile, FilePath);
                    }
                    LastFileRead = GetLastFileModificationUTC(FilePath);
                }
            }
            catch (IOException e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                throw;
            }
        }
Example #14
0
        public void createXML(string XmlFilePath, StringBuilder str)
        {
            //   XmlFilePath = this.XmlFilePath;
            try
            {
                if (!File.Exists(XmlFilePath))
                {
                    XmlTextWriter textWritter = new XmlTextWriter(XmlFilePath, Encoding.UTF8);

                    textWritter.WriteStartDocument();

                    textWritter.WriteStartElement("book");

                    textWritter.WriteEndElement();

                    textWritter.Close();
                   // Console.WriteLine("Xml have been created!");
                }
                else
                {
                    //Console.WriteLine("File haven't been created. Xml already exist!");

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            addData(XmlFilePath,str);
        }
Example #15
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 #16
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 #17
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 #18
0
        /// <summary>
        /// Saves settings to an XML file
        /// </summary>
        /// <param name="file">The file to save to</param>
        internal static void SaveSettings(string file)
        {
            try
            {
                // Open writer
                System.Xml.XmlTextWriter xmlwriter = new System.Xml.XmlTextWriter(file, System.Text.Encoding.Default);
                xmlwriter.Formatting = System.Xml.Formatting.Indented;

                // Start document
                xmlwriter.WriteStartDocument();
                xmlwriter.WriteStartElement("KMLImporter");

                // ShowAllLabels
                xmlwriter.WriteStartElement("ShowAllLabels");
                xmlwriter.WriteString(ShowAllLabels.ToString(CultureInfo.InvariantCulture));
                xmlwriter.WriteEndElement();

                // End document
                xmlwriter.WriteEndElement();
                xmlwriter.WriteEndDocument();

                // Close writer
                xmlwriter.Flush();
                xmlwriter.Close();
            }
            catch (System.IO.IOException)
            { }
            catch (System.Xml.XmlException)
            { }
        }
Example #19
0
 public static void CreateXml(string path)
 {
     XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8) {
         Formatting = Formatting.Indented
     };
     writer.WriteStartDocument();
     writer.WriteStartElement("root");
     for (int i = 0; i < 5; i++)
     {
         writer.WriteStartElement("Node");
         writer.WriteAttributeString("Text", "这是文章内容!~!!~~");
         writer.WriteAttributeString("ImageUrl", "");
         writer.WriteAttributeString("NavigateUrl", "Url..." + i.ToString());
         writer.WriteAttributeString("Expand", "true");
         for (int j = 0; j < 5; j++)
         {
             writer.WriteStartElement("Node");
             writer.WriteAttributeString("Text", "......名称");
             writer.WriteAttributeString("NavigateUrl", "Url..." + i.ToString());
             writer.WriteEndElement();
         }
         writer.WriteEndElement();
     }
     writer.WriteFullEndElement();
     writer.Close();
 }
        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 #21
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" );
            }
        }
Example #22
0
    /// <summary>
    /// Write the macro in the RichTextBox to a macro name provided.
    /// </summary>
    /// <param name="fileName">Name of Macro to write (macro name, not file path).</param>
    private void WriteToFile(string fileName)
    {
      _macroFile = fileName;

      try
      {
        using (XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8))
        {
          writer.Formatting = Formatting.Indented;
          writer.WriteStartDocument(true);
          writer.WriteStartElement("macro");

          foreach (string item in richTextBoxMacro.Lines)
          {
            if (String.IsNullOrEmpty(item))
              continue;

            writer.WriteStartElement("item");
            writer.WriteAttributeString("command", item);
            writer.WriteEndElement();
          }

          writer.WriteEndElement();
          writer.WriteEndDocument();
        }
      }
      catch (Exception ex)
      {
        IrssLog.Error(ex);
      }
    }
Example #23
0
        /* 08. 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.*/
        public static void Main()
        {
            using (XmlReader sr = XmlReader.Create("..\\..\\..\\catalog.xml"))
            {
                using (XmlTextWriter writer = new XmlTextWriter("..\\..\\album.xml", Encoding.UTF8))
                {
                    writer.WriteStartDocument();
                    writer.Formatting = Formatting.Indented;
                    writer.IndentChar = '\t';
                    writer.Indentation = 1;
                    writer.WriteStartElement("albums");
                    var name = string.Empty;
                    var artist = string.Empty;

                    while (sr.Read())
                    {
                        if ((sr.NodeType == XmlNodeType.Element) && (sr.Name == "name"))
                        {
                            name = sr.ReadElementString().Trim();
                        }
                        else if ((sr.NodeType == XmlNodeType.Element) && (sr.Name == "artist"))
                        {
                            artist = sr.ReadElementString().Trim();
                            WriteAlbumInnerXML(writer, name, artist);
                        }
                    }
                }
            }
        }
 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();
         }
     }
 }
Example #25
0
        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);
            }
        }
Example #26
0
        internal string Build()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (XmlTextWriter xml = new XmlTextWriter(ms, new UTF8Encoding(false)) { Formatting = Formatting.Indented })
                {
                    xml.WriteStartDocument();

                    string license = this.GetLicense();
                    xml.WriteComment(license);

                    xml.WriteStartElement("MixERPReport");
                    xml.WriteElementString("Title", this.Definition.Title);

                    this.WriteTopSection(xml);
                    this.WriteBody(xml);
                    this.WriteBottomSection(xml);

                    this.WriteDataSources(xml);

                    this.WriteMenu(xml);
                }

                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
Example #27
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 #28
0
        public static void WriteData()
        {
            if (!Directory.Exists(SR_Main.SavePath))
                Directory.CreateDirectory(SR_Main.SavePath);

            string filePath = Path.Combine(SR_Main.SavePath, SR_Main.FileName);

            using (StreamWriter op = new StreamWriter(filePath))
            {
                XmlTextWriter xml = new XmlTextWriter(op);

                xml.Formatting = Formatting.Indented;
                xml.IndentChar = '\t';
                xml.Indentation = 1;

                xml.WriteStartDocument(true);

                xml.WriteStartElement("StaffRunebook");

                xml.WriteAttributeString("Version", SR_Main.Version.ToString());

                for (int i = 0; i < SR_Main.Count; i++)
                    WriteAccountNode(SR_Main.Info[i], xml);

                xml.WriteEndElement();

                xml.Close();
            }
        }
Example #29
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 #30
0
        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!");
        }
Example #31
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 ) );
        }
Example #32
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;
        }
        /// <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();
            }
        }
Example #34
0
        /// <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;
        }
Example #35
0
        private void DumpInputs()
        {
            try
            {
                System.Reflection.Assembly currentAssembly = System.Reflection.Assembly.GetAssembly(typeof(MainForm));
                FileInfo assemblyFileInfo = new FileInfo(currentAssembly.Location);

                System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(assemblyFileInfo.DirectoryName + @"\init.xml", null);

                xw.Formatting  = System.Xml.Formatting.Indented;
                xw.Indentation = 2;
                xw.WriteStartDocument();
                xw.WriteStartElement("Robocopy_GUI");


                xw.WriteStartElement("Source");
                xw.WriteString(this.textSource.Text);
                xw.WriteEndElement();

                xw.WriteStartElement("Destination");
                xw.WriteString(this.textDestination.Text);
                xw.WriteEndElement();


                xw.WriteEndElement();
                xw.WriteEndDocument();
                xw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, ex.Source);
            }
        }
Example #36
0
        private void SaveSetting()
        {
            //throw new System.NotImplementedException();

            #region zhucebiao
            //RegistryKey softwareKey = Registry.LocalMachine.OpenSubKey("SoftWare", true);
            //RegistryKey SQKey = softwareKey.CreateSubKey("SQPress");
            //RegistryKey selfWindowsKey = SQKey.CreateSubKey("selfWindowsKey");
            //selfWindowsKey.SetValue("BackColor", (object)BackColor.ToKnownColor());
            //selfWindowsKey.SetValue("Red", (object)(int)BackColor.R);
            //selfWindowsKey.SetValue("Green", (object)(int)BackColor.G);
            //selfWindowsKey.SetValue("Blue", (object)(int)BackColor.B);
            //selfWindowsKey.SetValue("Width", (object)Width);
            //selfWindowsKey.SetValue("Height", (object)Height);
            //selfWindowsKey.SetValue("X", (object)DesktopLocation.X);
            //selfWindowsKey.SetValue("Y", (object)DesktopLocation.Y);
            //selfWindowsKey.SetValue("WindowState", (object)WindowState.ToString());

            //softwareKey.Close();
            //SQKey.Close();
            //selfWindowsKey.Close();
            #endregion

            #region ISO
            IsolatedStorageFile iso         = IsolatedStorageFile.GetUserStoreForDomain();
            var isoStream                   = new IsolatedStorageFileStream("SelfPlace.xml", FileMode.Create, FileAccess.ReadWrite);
            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(isoStream, Encoding.Default);
            writer.Formatting = System.Xml.Formatting.Indented;


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

            writer.WriteStartElement("Width");
            writer.WriteValue(this.Width);
            writer.WriteEndElement();

            writer.WriteStartElement("Height");
            writer.WriteValue(this.Height);
            writer.WriteEndElement();

            writer.WriteStartElement("X");
            writer.WriteValue(this.DesktopLocation.X);
            writer.WriteEndElement();

            writer.WriteStartElement("Y");
            writer.WriteValue(this.DesktopLocation.Y);
            writer.WriteEndElement();

            writer.WriteEndElement();

            writer.Flush();
            writer.Close();

            isoStream.Close();
            iso.Close();
            #endregion
        }
Example #37
0
        /// <summary>
        /// 格式化日期类型
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        private XmlDocument DateTimeFormat(XmlDocument doc, List <string> eles)
        {
            if (eles == null || eles.Count == 0 || doc == null)
            {
                return(doc);
            }
            XmlDocument newDoc = new XmlDocument();

            try {
                // 建立一个 XmlTextReader 对象来读取 XML 数据。
                using (XmlTextReader myXmlReader = new XmlTextReader(doc.OuterXml, XmlNodeType.Element, null)) {
                    // 使用指定的文件与编码方式来建立一个 XmlTextWriter 对象。
                    using (System.Xml.XmlTextWriter myXmlWriter = new System.Xml.XmlTextWriter(_filePath, Encoding.UTF8)) {
                        myXmlWriter.Formatting  = Formatting.Indented;
                        myXmlWriter.Indentation = 4;
                        myXmlWriter.WriteStartDocument();

                        string elementName = "";

                        // 解析并显示每一个节点。
                        while (myXmlReader.Read())
                        {
                            switch (myXmlReader.NodeType)
                            {
                            case XmlNodeType.Element:
                                myXmlWriter.WriteStartElement(myXmlReader.Name);
                                myXmlWriter.WriteAttributes(myXmlReader, true);
                                elementName = myXmlReader.Name;

                                break;

                            case XmlNodeType.Text:
                                if (eles.Contains(elementName))
                                {
                                    myXmlWriter.WriteString(XmlConvert.ToDateTime(myXmlReader.Value, XmlDateTimeSerializationMode.Local).ToString("yyyy-MM-dd HH:mm:ss"));
                                    break;
                                }
                                myXmlWriter.WriteString(myXmlReader.Value);
                                break;

                            case XmlNodeType.EndElement:
                                myXmlWriter.WriteEndElement();
                                break;
                            }
                        }
                    }
                }
                newDoc.Load(_filePath);
                return(newDoc);
            } catch (Exception ex) {
                MessageBoxPLM.Show(string.Format("导入ERP文件格式化失败,错误信息:{0}", ex.Message));
                return(null);
            }
        }
        protected override void WriteSettings(string fileName)
        {
            using (System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(fileName, Encoding.UTF8))
            {
                xtw.Formatting = Formatting.Indented;
                xtw.WriteStartDocument();
                xtw.WriteStartElement("dictionary");

                EncodedNameMap.WriteXml(xtw);
                xtw.WriteEndElement();
            }
        }
Example #39
0
        /// <summary>
        /// 从DataTable和对应的GroupBox中的内容得到XML串
        /// </summary>
        /// <param name="p_objclsElementAttributeArr">p_dtbTable列数 ==p_objclsElementAttributeArr的长度(GroupBox中各项+签名+时间,每项对应一个clsElementAttribute对象)</param>
        /// <param name="p_dtbTable">记录对应的DataTable</param>
        /// <param name="p_objXmlMemStream"></param>
        /// <param name="p_xmlWriter"></param>
        /// <returns>若参数错误返回null</returns>
        public string m_strGetXMLFromDataTable(clsElementAttribute[] p_objclsElementAttributeArr, System.Data.DataTable p_dtbTable, ref System.IO.MemoryStream p_objXmlMemStream, ref System.Xml.XmlTextWriter p_xmlWriter)
        {
            if (p_objclsElementAttributeArr == null || p_dtbTable.Columns.Count != p_objclsElementAttributeArr.Length)
            {
                return(null);
            }

            p_objXmlMemStream.SetLength(0);
            p_xmlWriter.WriteStartDocument();
            p_xmlWriter.WriteStartElement("Main");

            clsElementAttribute objclsElementAttribute = new clsElementAttribute();

            bool blnIsModified = m_blnIsModified(p_objclsElementAttributeArr, p_dtbTable);

            if (blnIsModified == true)         //如果被修改,添加当前值
            {
                p_xmlWriter.WriteStartElement("Sub");
                for (int j0 = 0; j0 < p_objclsElementAttributeArr.Length; j0++)
                {
                    m_mthAddElementAttibute(p_objclsElementAttributeArr[j0], ref p_xmlWriter);
                }
                p_xmlWriter.WriteEndElement();
            }
            for (int i1 = 0; i1 < p_dtbTable.Rows.Count; i1++)     //重写原来的痕迹
            {
                p_xmlWriter.WriteStartElement("Sub");
                for (int j2 = 0; j2 < p_objclsElementAttributeArr.Length; j2++)
                {
                    objclsElementAttribute.m_blnIsDST       = p_objclsElementAttributeArr[j2].m_blnIsDST;            //默认为非DST格式,即为bool类型
                    objclsElementAttribute.m_strElementName = p_objclsElementAttributeArr[j2].m_strElementName;
                    if (objclsElementAttribute.m_blnIsDST == false)
                    {
                        objclsElementAttribute.m_strValue = p_dtbTable.Rows[i1][j2].ToString();
                    }
                    else
                    {
                        objclsElementAttribute.m_strValue    = ((clsDSTRichTextBoxValue)(p_dtbTable.Rows[i1][j2])).m_strText;
                        objclsElementAttribute.m_strValueXML = ((clsDSTRichTextBoxValue)(p_dtbTable.Rows[i1][j2])).m_strDSTXml;
                    }

                    m_mthAddElementAttibute(objclsElementAttribute, ref p_xmlWriter);
                }
                p_xmlWriter.WriteEndElement();
            }

            p_xmlWriter.WriteEndElement();
            p_xmlWriter.WriteEndDocument();
            p_xmlWriter.Flush();
            return(System.Text.Encoding.Unicode.GetString(p_objXmlMemStream.ToArray(), 39 * 2, (int)p_objXmlMemStream.Length - 39 * 2));
        }
Example #40
0
        public override void Write(System.IO.Stream stream)
        {
            if (this.RootChunk != null)
            {
                Xml.XmlTextWriter writer = new Xml.XmlTextWriter(stream, Encoding.UTF8);
                writer.Formatting = Xml.Formatting.Indented;

                writer.WriteStartDocument();

                WriteStep(writer, this.RootChunk);

                writer.WriteEndDocument();

                writer.Close();
            }
        }
Example #41
0
        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();
        }
Example #42
0
        /// <summary>
        /// 生成XML
        /// </summary>
        /// <param name="root">根结点</param>
        /// <returns></returns>
        public static String ToXml(XmlTreeNode root, Encoding encoding)
        {
            MemoryStream ms = new MemoryStream();
            XmlWriter    xw = new System.Xml.XmlTextWriter(ms, encoding);

            xw.WriteStartDocument();
            _WriteTreeNode(root, xw);
            xw.WriteEndDocument();

            xw.Flush();
            xw.Close();

            var xml = encoding.GetString(ms.ToArray());

            return(xml);
        }
Example #43
0
        /// <summary>
        /// creates logfile
        /// </summary>
        private void open()
        {
            if (this.opened_)
            {
                return;
            }
            try
            {
                if (theSwitch.Level > TraceLevel.Off)
                {
                    xmlwriter            = new System.Xml.XmlTextWriter(this.file_path, null);
                    xmlwriter.Formatting = System.Xml.Formatting.Indented;
                    xmlwriter.WriteStartDocument();
                    //Write the ProcessingInstruction node.
                    string PItext = theSwitch.style_instruction_pitext(string.Empty);
                    if (PItext != string.Empty)
                    {
                        xmlwriter.WriteProcessingInstruction("xml-stylesheet", PItext);
                    }

                    xmlwriter.WriteStartElement("trace");
                    xmlwriter.WriteAttributeString("timestamp", timestamp());
                    xmlwriter.WriteAttributeString("assembly", this.asm.FullName);
                    xmlwriter.WriteStartElement("switch");
                    // xmlwriter.WriteAttributeString( "displayname" , theSwitch.DisplayName) ;
                    // xmlwriter.WriteAttributeString( "description" , theSwitch.Description ) ;
                    xmlwriter.WriteAttributeString("level", theSwitch.Level.ToString());
                    xmlwriter.WriteEndElement();                     // close 'switch'
                }
                this.opened_ = true;
            }
            catch (Exception x)
            {
                evlog.internal_log.error(x); x = null;
            }
            finally
            {
                if (this.xmlwriter != null)
                {
                    xmlwriter.Close();
                }
                this.xmlwriter = null;
            }
        }
Example #44
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            thread_showSth();
            txtMsg.Text = "";

            xmlWriter            = new XmlTextWriter(Server.MapPath("./1234.xml"), System.Text.Encoding.UTF8);
            xmlWriter.Formatting = Formatting.Indented;
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("队列");
            xmlWriter.WriteStartElement("跳舞");
            xmlWriter.WriteString("boy,girl");
            xmlWriter.WriteEndElement();
            //写文档结束,调用WriteEndDocument方法
            xmlWriter.WriteEndDocument();
            // 关闭textWriter
            xmlWriter.Close();
        }
    }
Example #45
0
        public string ConvertProject(string xsltPath, string projectName)
        {
            var xTrf    = new System.Xml.Xsl.XslCompiledTransform(true);
            var xTrfArg = new System.Xml.Xsl.XsltArgumentList();
            var xSet    = new System.Xml.Xsl.XsltSettings(true, true);
            var wSet    = new System.Xml.XmlWriterSettings();
            var mstr    = new System.Xml.XmlTextWriter(new System.IO.MemoryStream(), System.Text.Encoding.UTF8);
            //var mstr = new System.Xml.XmlTextWriter(xsltPath + "test.xml", System.Text.Encoding.UTF8);
            var doc = new System.Xml.XmlDocument();

            wSet = xTrf.OutputSettings;
            xTrf.Load(CopyXSLTFile(xsltPath), xSet, new XmlUrlResolver());
            xTrfArg.AddParam("ProjectName", "", projectName);
            mstr.WriteStartDocument();
            mstr.WriteDocType("Article", "-//RiQuest Software//DTD JBArticle v1.0 20020724//EN", "../dtd/JBArticle/jbarticle.dtd", null);
            xTrf.Transform(_extractPath + "/desktop.xml", xTrfArg, mstr);
            mstr.BaseStream.Flush();
            mstr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            return(new StreamReader(mstr.BaseStream).ReadToEnd());
        }
Example #46
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 #47
0
    /// <summary>
    /// Flushes the hashtable to the xml file
    /// </summary>
    public void Flush()
    {
        if (isRoot)
        {
            Xml.XmlTextWriter writer = new Xml.XmlTextWriter(this.fileName, System.Text.Encoding.ASCII);

            try
            {
                //			writer.Formatting = Xml.Formatting.Indented;

                writer.WriteStartDocument(true);
                writer.WriteStartElement(rootName);

                WriteElements(writer);

                writer.WriteEndElement();
            }
            finally
            {
                writer.Close();
            }
        }
    }
Example #48
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();
                }
            }
        /// <summary> Writes the mapping of the specified class in the specified stream. </summary>
        /// <param name="stream">Where the xml is written; can be null if you send the writer.</param>
        /// <param name="type">User-defined type containing a valid attribute (can be [Class] or [xSubclass]).</param>
        /// <param name="writer">The XmlTextWriter used to write the xml; can be null if you send the stream. You can also create it yourself, but don't forget to write the StartElement ("hibernate-mapping") before.</param>
        /// <param name="writeEndDocument">Tells if the EndElement of "hibernate-mapping" must be written; send false to append many classes in the same stream.</param>
        /// <returns>The parameter writer if it was not null; else it is a new writer (created using the stream). Send it back to append many classes in this stream.</returns>
        public virtual System.Xml.XmlTextWriter Serialize(System.IO.Stream stream, System.Type type, System.Xml.XmlTextWriter writer, bool writeEndDocument)
        {
            if (stream == null && writer == null)
            {
                throw new System.ArgumentNullException("stream");
            }
            if (type == null)
            {
                throw new System.ArgumentNullException("type");
            }

            if (writer == null)
            {
                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 by NHibernate.Mapping.Attributes on {0}.", System.DateTime.Now.ToString("u")));
                }
                WriteHibernateMapping(writer, type);
            }

            if (IsClass(type))
            {
                HbmWriter.WriteClass(writer, type);
            }
            else if (IsSubclass(type, typeof(SubclassAttribute)))
            {
                HbmWriter.WriteSubclass(writer, type);
            }
            else if (IsSubclass(type, typeof(JoinedSubclassAttribute)))
            {
                HbmWriter.WriteJoinedSubclass(writer, type);
            }
            else if (IsSubclass(type, typeof(UnionSubclassAttribute)))
            {
                HbmWriter.WriteUnionSubclass(writer, type);
            }
            else
            {
                throw new System.ArgumentException("No valid attribute; looking for [Class] or [xSubclass].", "type");
            }

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

                if (!Validate)
                {
                    return(writer);
                }

                // Validate the generated XML stream
                try
                {
                    writer.BaseStream.Position = 0;
                    var 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);
                }
            }
            else
            {
                writer.Flush();
            }

            return(writer);
        }
Example #50
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 #52
0
        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();
        }
Example #53
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";
        }
        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 #55
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;
            }
        }
Example #56
0
        // Constructor
        public Hxc(string name, string title, string langId, string version, string copyright, string outputDirectory, Encoding encoding)
        {
            if (!Directory.Exists(outputDirectory))
            {
                try
                {
                    Directory.CreateDirectory(outputDirectory);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            try
            {
                System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Path.Combine(outputDirectory, name + ".hxc"), null);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                writer.WriteDocType("HelpCollection", null, "MS-Help://Hx/Resources/HelpCollection.dtd", null);

                writer.WriteStartElement("HelpCollection");
                writer.WriteAttributeString("DTDVersion", "1.0");
                writer.WriteAttributeString("FileVersion", version);
                writer.WriteAttributeString("LangId", langId);
                writer.WriteAttributeString("Title", title);
                writer.WriteAttributeString("Copyright", copyright);

                writer.WriteStartElement("CompilerOptions");
                writer.WriteAttributeString("OutputFile", string.Format("{0}{1}", name, ".HxS"));
                writer.WriteAttributeString("CreateFullTextIndex", "Yes");
                writer.WriteAttributeString("CompileResult", "Hxs");
                writer.WriteAttributeString("StopWordFile", "msdnFTSstop_Unicode.stp");

                writer.WriteStartElement("IncludeFile");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, ".HxF"));
                writer.WriteEndElement();

                writer.WriteEndElement();

                writer.WriteStartElement("TOCDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, ".HxT"));
                writer.WriteEndElement();

                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "K.HxK"));
                writer.WriteEndElement();
                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "F.HxK"));
                writer.WriteEndElement();
                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "N.HxK"));
                writer.WriteEndElement();
                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "A.HxK"));
                writer.WriteEndElement();
                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "S.HxK"));
                writer.WriteEndElement();
                writer.WriteStartElement("KeywordIndexDef");
                writer.WriteAttributeString("File", string.Format("{0}{1}", name, "B.HxK"));
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultTOC" ProgId="HxDs.HxHierarchy" InitData="AnyString" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultTOC");
                writer.WriteAttributeString("ProgId", "HxDs.HxHierarchy");
                writer.WriteAttributeString("InitData", "AnyString");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultFullTextSearch" ProgId="HxDs.HxFullTextSearch" InitData="AnyString" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultFullTextSearch");
                writer.WriteAttributeString("ProgId", "HxDs.HxFullTextSearch");
                writer.WriteAttributeString("InitData", "AnyString");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultAssociativeIndex" ProgId="HxDs.HxIndex" InitData="A" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultAssociativeIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "A");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultKeywordIndex" ProgId="HxDs.HxIndex" InitData="K" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultKeywordIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "K");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultContextWindowIndex" ProgId="HxDs.HxIndex" InitData="F" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultContextWindowIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "F");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultNamedUrlIndex" ProgId="HxDs.HxIndex" InitData="NamedUrl" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultNamedUrlIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "NamedUrl");
                writer.WriteEndElement();

                //  <ItemMoniker Name="!DefaultSearchWindowIndex" ProgId="HxDs.HxIndex" InitData="S" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultSearchWindowIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "S");
                writer.WriteEndElement();


                //  <ItemMoniker Name="!DefaultDynamicLinkIndex" ProgId="HxDs.HxIndex" InitData="B" />
                writer.WriteStartElement("ItemMoniker");
                writer.WriteAttributeString("Name", "!DefaultDynamicLinkIndex");
                writer.WriteAttributeString("ProgId", "HxDs.HxIndex");
                writer.WriteAttributeString("InitData", "B");
                writer.WriteEndElement();

                writer.WriteEndElement();
                writer.Flush();
                writer.Close();
                writer = null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <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 #58
0
        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();
        }
Example #59
0
        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();
        }