public QueryOutputWriterV1(XmlWriter writer, XmlWriterSettings settings) { _wrapped = writer; _systemId = settings.DocTypeSystem; _publicId = settings.DocTypePublic; if (settings.OutputMethod == XmlOutputMethod.Xml) { bool documentConformance = false; // Xml output method shouldn't output doc-type-decl if system ID is not defined (even if public ID is) // Only check for well-formed document if output method is xml if (_systemId != null) { documentConformance = true; _outputDocType = true; } // Check for well-formed document if standalone="yes" in an auto-generated xml declaration if (settings.Standalone == XmlStandalone.Yes) { documentConformance = true; _standalone = settings.Standalone; } if (documentConformance) { if (settings.Standalone == XmlStandalone.Yes) { _wrapped.WriteStartDocument(true); } else { _wrapped.WriteStartDocument(); } } if (settings.CDataSectionElements != null && settings.CDataSectionElements.Count > 0) { _bitsCData = new BitStack(); _lookupCDataElems = new Dictionary<XmlQualifiedName, XmlQualifiedName>(); _qnameCData = new XmlQualifiedName(); // Add each element name to the lookup table foreach (XmlQualifiedName name in settings.CDataSectionElements) { _lookupCDataElems[name] = null; } _bitsCData.PushBit(false); } } else if (settings.OutputMethod == XmlOutputMethod.Html) { // Html output method should output doc-type-decl if system ID or public ID is defined if (_systemId != null || _publicId != null) _outputDocType = true; } }
public bool startDocument(string version = DefaultXmlVersion, string encoding = null, string standalone = null) { if (version != DefaultXmlVersion) { PhpException.ArgumentValueNotSupported(nameof(version), version); } if (encoding != null && !string.Equals(encoding, "utf-8", StringComparison.CurrentCultureIgnoreCase)) { PhpException.ArgumentValueNotSupported(nameof(encoding), encoding); } if (string.IsNullOrEmpty(standalone)) { bool res = CheckedCall(() => _writer.WriteStartDocument()); if (!_writer.Settings.Indent) // Php writes a new line character after prolog. { res &= CheckedCall(() => _writer.WriteRaw(_writer.Settings.NewLineChars)); } return(res); } else { bool res = CheckedCall(() => _writer.WriteStartDocument(standalone == "yes")); if (!_writer.Settings.Indent) // Php writes a new line character after prolog. { res &= CheckedCall(() => _writer.WriteRaw(_writer.Settings.NewLineChars)); } return(res); } }
public virtual void WriteDocument(Stream stream, TagCompound tag, CompressionOption compression) { bool createWriter; if (compression == CompressionOption.On) { throw new NotSupportedException("Compression is not supported."); } createWriter = _writer == null; if (createWriter) { XmlWriterSettings settings; settings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 }; _writer = XmlWriter.Create(stream, settings); _writer.WriteStartDocument(true); } this.WriteTag(tag, WriteTagOptions.None); if (createWriter) { _writer.WriteEndDocument(); _writer.Flush(); _writer = null; } }
public virtual string ToDescriptionDocument() { if (String.IsNullOrEmpty(this.Uuid)) throw new InvalidOperationException("Must provide a UUID value."); //This would have been so much nicer with Xml.Linq, but that's //not available until .NET 4.03 at the earliest, and I want to //target 4.0 :( using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(ms, new XmlWriterSettings() { Encoding = System.Text.UTF8Encoding.UTF8, Indent = true, NamespaceHandling = NamespaceHandling.OmitDuplicates }); writer.WriteStartDocument(); writer.WriteStartElement("root", SsdpConstants.SsdpDeviceDescriptionXmlNamespace); writer.WriteStartElement("specVersion"); writer.WriteElementString("major", "1"); writer.WriteElementString("minor", "0"); writer.WriteEndElement(); if (this.UrlBase != null && this.UrlBase != this.Location) writer.WriteElementString("URLBase", this.UrlBase.ToString()); WriteDeviceDescriptionXml(writer, this); writer.WriteEndElement(); writer.Flush(); ms.Seek(0, System.IO.SeekOrigin.Begin); using (var reader = new System.IO.StreamReader(ms)) { return reader.ReadToEnd(); } } }
public static void WriteXmlLogStart(XmlWriter xw) { xw.WriteStartDocument(); xw.WriteStartElement("LogEntries"); xw.WriteString("\r\n"); xw.WriteComment(StaticVariables.Logo(false) + "\r\n" + CurrentQuery + "\r\n"); //+ CurrentEntryCount + "\r\n"); }
public void Serialize(DbDatabaseMapping databaseMapping, XmlWriter xmlWriter) { DebugCheck.NotNull(xmlWriter); DebugCheck.NotNull(databaseMapping); Debug.Assert(databaseMapping.Model != null); Debug.Assert(databaseMapping.Database != null); _xmlWriter = xmlWriter; _databaseMapping = databaseMapping; _version = databaseMapping.Model.SchemaVersion; _namespace = Equals(_version, XmlConstants.EdmVersionForV3) ? EdmXmlNamespaceV3 : (Equals(_version, XmlConstants.EdmVersionForV2) ? EdmXmlNamespaceV2 : EdmXmlNamespaceV1); _xmlWriter.WriteStartDocument(); using (Element("Edmx", "Version", string.Format(CultureInfo.InvariantCulture, "{0:F1}", _version))) { WriteEdmxRuntime(); WriteEdmxDesigner(); } _xmlWriter.WriteEndDocument(); _xmlWriter.Flush(); }
public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; response.ClearContent(); response.ContentType = "text/xml"; response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xml", _exportName)); var settings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8, ConformanceLevel = ConformanceLevel.Document, CheckCharacters = true, NamespaceHandling = NamespaceHandling.OmitDuplicates }; _writer = XmlWriter.Create(response.OutputStream, settings); _writer.WriteStartDocument(true); AddItem(_blob, _rootName, true); _writer.WriteEndDocument(); _writer.Flush(); _writer = null; }
/// <summary> /// Write the settings provided to stream /// </summary> /// <param name="inputStream"></param> /// <returns></returns> public static void SerializeAnalyticsSettings(XmlWriter xmlWriter, AnalyticsSettings settings) { xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement(SettingsSerializerHelper.RootPropertiesElementName); //LOGGING STARTS HERE xmlWriter.WriteStartElement(SettingsSerializerHelper.LoggingElementName); xmlWriter.WriteStartElement(SettingsSerializerHelper.VersionElementName); xmlWriter.WriteValue(settings.LogVersion); xmlWriter.WriteEndElement(); bool isReadEnabled = (settings.LogType & LoggingLevel.Read) != LoggingLevel.None; xmlWriter.WriteStartElement(SettingsSerializerHelper.ApiTypeReadElementName); xmlWriter.WriteValue(isReadEnabled); xmlWriter.WriteEndElement(); bool isWriteEnabled = (settings.LogType & LoggingLevel.Write) != LoggingLevel.None; xmlWriter.WriteStartElement(SettingsSerializerHelper.ApiTypeWriteElementName); xmlWriter.WriteValue(isWriteEnabled); xmlWriter.WriteEndElement(); bool isDeleteEnabled = (settings.LogType & LoggingLevel.Delete) != LoggingLevel.None; xmlWriter.WriteStartElement(SettingsSerializerHelper.ApiTypeDeleteElementName); xmlWriter.WriteValue(isDeleteEnabled); xmlWriter.WriteEndElement(); SerializeRetentionPolicy(xmlWriter, settings.IsLogRetentionPolicyEnabled, settings.LogRetentionInDays); xmlWriter.WriteEndElement(); // logging element //METRICS STARTS HERE xmlWriter.WriteStartElement(SettingsSerializerHelper.MetricsElementName); xmlWriter.WriteStartElement(SettingsSerializerHelper.VersionElementName); xmlWriter.WriteValue(settings.MetricsVersion); xmlWriter.WriteEndElement(); bool isServiceSummaryEnabled = (settings.MetricsType & MetricsType.ServiceSummary) != MetricsType.None; xmlWriter.WriteStartElement(SettingsSerializerHelper.MetricsEnabledElementName); xmlWriter.WriteValue(isServiceSummaryEnabled); xmlWriter.WriteEndElement(); if (isServiceSummaryEnabled) { bool isApiSummaryEnabled = (settings.MetricsType & MetricsType.ApiSummary) != MetricsType.None; xmlWriter.WriteStartElement(SettingsSerializerHelper.IncludeApiSummaryElementName); xmlWriter.WriteValue(isApiSummaryEnabled); xmlWriter.WriteEndElement(); } SerializeRetentionPolicy( xmlWriter, settings.IsMetricsRetentionPolicyEnabled, settings.MetricsRetentionInDays); xmlWriter.WriteEndElement(); // metrics xmlWriter.WriteEndElement(); // root element xmlWriter.WriteEndDocument(); }
// This method creates Xml with a point write it to a file and returns it in a string form public string ToXmlSave() { // getting all needed values from FlightGear string lon = Client.Instance.getInfo("get " + LON_DEG); string lat = Client.Instance.getInfo("get " + LAT_DEG); string rudder = Client.Instance.getInfo("get " + RUDDER_PATH); string throttle = Client.Instance.getInfo("get " + THROTTLE_PATH); // creating object pointEntry to send to function that saves data to file PointEntry pointEntry = new PointEntry(lat, lon, rudder, throttle); // calling function that writes data of specific point to file Models.DataWriter.Instance.WriteData(pointEntry, (string)Session["fileName"]); // after saving point to xml file, send it to view StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings); writer.WriteStartDocument(); writer.WriteStartElement("Point"); writer.WriteElementString("lon", lon); writer.WriteElementString("lat", lat); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); return(sb.ToString()); }
public void Serialize(DbDatabaseMapping databaseMapping, DbProviderInfo providerInfo, XmlWriter xmlWriter) { //Contract.Requires(xmlWriter != null); //Contract.Requires(databaseMapping != null); //Contract.Requires(providerInfo != null); Contract.Assert(databaseMapping.Model != null); Contract.Assert(databaseMapping.Database != null); _xmlWriter = xmlWriter; _databaseMapping = databaseMapping; _version = databaseMapping.Model.Version; _providerInfo = providerInfo; _namespace = _version == DataModelVersions.Version3 ? EdmXmlNamespaceV3 : EdmXmlNamespaceV2; _xmlWriter.WriteStartDocument(); using (Element("Edmx", "Version", string.Format(CultureInfo.InvariantCulture, "{0:F1}", _version))) { WriteEdmxRuntime(); WriteEdmxDesigner(); } _xmlWriter.WriteEndDocument(); _xmlWriter.Flush(); }
private void Click_Save(object sender, RoutedEventArgs e) { System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(Environment.CurrentDirectory + @"\" + FileName); writer.WriteStartDocument(); if (cvs.Children.Count != 0) { writer.WriteStartElement("Icons"); foreach (var i in cvs.Children) { var im = (Image)i; writer.WriteStartElement("Icon"); writer.WriteElementString("Source", im.Source + ""); writer.WriteElementString("Width", im.Width + ""); writer.WriteElementString("Height", im.Height + ""); writer.WriteElementString("Left", im.GetValue(Canvas.LeftProperty) + ""); writer.WriteElementString("Top", im.GetValue(Canvas.TopProperty) + ""); writer.WriteEndElement(); writer.Flush(); } writer.WriteEndElement(); writer.WriteEndDocument(); } else { writer.WriteStartElement("Null"); writer.WriteEndElement(); writer.WriteEndDocument(); } writer.Close(); MessageBox.Show("Позиции иконок сохранены!", "Perfect", MessageBoxButton.OK, MessageBoxImage.Information); }
// ---------------------------------------------------------- public void Minimize(Options aOptions, Def aDef) { // reader _reader = new XmlDocument(); _reader.Load(aOptions.inFile); // writter with write settings var writterSettings = new XmlWriterSettings(); if (aOptions.prettyPrint) { writterSettings.Indent = true; writterSettings.IndentChars = " "; } _writer = XmlWriter.Create(aOptions.outFile, writterSettings); _writer.WriteStartDocument(); ProcessElement(_reader.DocumentElement, aDef); _writer.WriteEndDocument(); _writer.Close(); // print warnings foreach(string warning in _warnings) { Console.WriteLine(warning); } }
public void Render(System.Xml.XmlWriter writer) { writer.WriteStartDocument(true); writer.WriteStartElement("", "Customer", "mvp-xml-templates"); writer.WriteAttributeString("", "xmlns", "http://www.w3.org/2000/xmlns/", "mvp-xml-templates"); writer.WriteAttributeString("", "Name", "", Converter.ToString(customer.LastName + ", " + customer.FirstName)); writer.WriteStartElement("", "Orders", "mvp-xml-templates"); foreach (Order o in customer.Orders) //; { writer.WriteStartElement("", "Order", "mvp-xml-templates"); writer.WriteAttributeString("", "Id", "", Converter.ToString(o.Id)); writer.WriteAttributeString("", "Premium", "", Converter.ToString((o.GrandTotal > 10000))); writer.WriteStartElement("", "Items", "mvp-xml-templates"); writer.WriteAttributeString("", "GrandTotal", "", Converter.ToString(CalculateTotals(o))); foreach (Item i in o.Items) //; { writer.WriteStartElement("", "Item", "mvp-xml-templates"); writer.WriteAttributeString("", "Id", "", Converter.ToString(i.ProductId)); writer.WriteAttributeString("", "SubTotal", "", Converter.ToString(i.Quantity * i.Price)); writer.WriteEndElement(); }//; writer.WriteEndElement(); writer.WriteStartElement("", "Recipe", "http://schemas.microsoft.com/pag/gax-core"); writer.WriteAttributeString("", "xmlns", "http://www.w3.org/2000/xmlns/", "http://schemas.microsoft.com/pag/gax-core"); writer.WriteAttributeString("", "Name", "", "Foo"); writer.WriteStartElement("", "Caption", "http://schemas.microsoft.com/pag/gax-core"); writer.WriteString(Converter.ToString(o.DateOrdered)); writer.WriteEndElement(); writer.WriteStartElement("", "Description", "http://schemas.microsoft.com/pag/gax-core"); writer.WriteString(("\n\t\t\t\t\tExample of escaping the curly braces: \n\t\t\t\t\tstring.Format(\"" + (Converter.ToString({ 0 })
internal void XmlWriter(string filePath, string fileName, string subRootNode /*,List<CustomClass> customClass*/) { string completeFilepath = Path.Combine(filePath, fileName); using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(completeFilepath)) { writer.WriteStartDocument(); //Assuming fileName is same as the Root Node name writer.WriteStartElement(fileName); #region ForeachLoop //foreach (CustomClass customClass in customClass) //{ // writer.WriteStartElement(subRootNode); // writer.WriteElementString("ID", customClass.Id.ToString()); // writer.WriteElementString("FirstName", customClass.FirstName); // writer.WriteElementString("LastName", customClass.LastName); // //Add the writer.WriteElementString based on the number of member variable in CustomClass // writer.WriteEndElement(); //} #endregion writer.WriteEndElement(); writer.WriteEndDocument(); } }
public RdfXmlWriter(XmlWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); _writer = writer; _writer.WriteStartDocument(); _writer.WriteStartElement("rdf", "RDF", RdfNamespace); }
private static void WriteBooksToXml( XmlWriter writer, List<Book> booklist ) { writer.WriteStartDocument(); { writer.WriteStartElement("bdd", "books", NS); //This adds the root element, <bdd:books>. foreach(Book book in booklist) { writer.WriteStartElement("bdd", "book", NS); //Adds the element <bdd:book>. writer.WriteAttributeString("language", NS, book.Language); //Adding attributes to the element we just started. writer.WriteAttributeString("pages", NS, book.Pages); { writer.WriteElementString("title", NS, book.Title); if(book.Subtitle != "") writer.WriteElementString("subtitle", NS, book.Subtitle); if(book.Authors != null) foreach(string author in book.Authors) writer.WriteElementString("author", NS, author); else writer.WriteElementString("author", NS, book.Author); writer.WriteElementString("publisher", NS, book.Publisher); writer.WriteElementString("year", NS, book.Year); } writer.WriteEndElement(); //Closes the <bdd:book> element. } writer.WriteEndElement(); //Closes the <bdd:books> element. } writer.WriteEndDocument(); }
public static void GravarLogAcesso() { List <string> logKeys = new List <string>(new string[] { "HTTP_USER_AGENT", "HTTP_REFERER", "QUERY_STRING", "REMOTE_ADDR" }); StringBuilder xml = new StringBuilder(); using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(xml)) { writer.WriteStartDocument(); writer.WriteStartElement("Dados"); foreach (string key in HttpContext.Current.Request.ServerVariables.AllKeys) { if (logKeys.Contains(key)) { writer.WriteStartElement("Item"); writer.WriteAttributeString("Key", key); writer.WriteCData(HttpContext.Current.Request.ServerVariables[key]); writer.WriteEndElement(); } } writer.WriteEndElement(); writer.WriteEndDocument(); } string atributo = xml.ToString().Replace("utf-16", "utf-8"); DatabaseUtil.Connector.BindSql("insert into log_acesso (cod_usuario, dat_acesso, dsc_atributo) values (?, ?, ?) "). ToParam("@Usuario", Convert.ToInt32(HttpContext.Current.Session["CodUsuario"])). ToParam("@Data", DateTime.Now). ToParam("@Atributo", atributo). Execute(); }
private void SaveGameDescriptor(Stream stream) { ISerializationService service = Services.GetService <ISerializationService>(); if (service != null) { XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace, OmitXmlDeclaration = true }; using (System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(stream, settings)) { xmlWriter.WriteStartDocument(); XmlSerializer xmlSerializer = service.GetXmlSerializer <GameSaveDescriptor>(); xmlSerializer.Serialize(xmlWriter, this.GameSaveDescriptor); xmlWriter.WriteEndDocument(); xmlWriter.Flush(); xmlWriter.Close(); } } }
// Private Methods //====================================================================== private void Write(XmlWriter outputWriter) { outputWriter.WriteStartDocument(); XStreamingElement root = MakeDzcTree(); root.WriteTo(outputWriter); }
// This method creates Xml read a point from the file and returns it in a string form public string ToXmlSavedFlight() { // reading data point from object that PointEntry nextPoint = DataReader.Instance.ReadData(); if (nextPoint == null) { return(null); } // after saving point to xml file, send it to view StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings); writer.WriteStartDocument(); writer.WriteStartElement("Point"); writer.WriteElementString("lon", nextPoint.lon); writer.WriteElementString("lat", nextPoint.lat); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); return(sb.ToString()); }
private void Write(XmlWriter outputWriter) { outputWriter.WriteStartDocument(); //Write the XML declaration XStreamingElement root = MakeCxmlTree(); root.WriteTo(outputWriter); }
protected virtual void _WriteStartRootNode ( System.Xml.XmlWriter xmlWriter, string name, string ns, NamespaceList nsList ) { xmlWriter.WriteStartDocument(true); xmlWriter.WriteStartElement(name, ns); if (nsList != null) { StringBuilder schemaLocation = new StringBuilder(); foreach (NamespaceData nsd in nsList) { if (String.IsNullOrEmpty(nsd.NamespaceUri) == true) { continue; } if (String.IsNullOrEmpty(nsd.Prefix) == false) { xmlWriter.WriteAttributeString("xmlns", nsd.Prefix, null, nsd.NamespaceUri); } if (String.IsNullOrEmpty(nsd.XSDLocation) == false) { schemaLocation.AppendFormat("{0} {1} ", nsd.NamespaceUri, nsd.XSDLocation); } } xmlWriter.WriteAttributeString("xsi", "schemaLocation", null, schemaLocation.ToString().Trim()); } }
public void Write() { XmlWriterSettings xmlSetting = new XmlWriterSettings(); xmlSetting.CloseOutput = true; xmlSetting.Encoding = Encoding.UTF8; xmlSetting.Indent = true; xmlSetting.NewLineChars = "\r\n"; wr = XmlWriter.Create(GeneralConfig.AppDataPath + "Questionaries\\" + questionary.Category + ".xml", xmlSetting); wr.WriteStartDocument(); wr.WriteStartElement("Questionary"); wr.WriteStartAttribute("category"); wr.WriteValue(questionary.Category); wr.WriteEndAttribute(); wr.WriteStartAttribute("created"); wr.WriteValue(questionary.Created.ToString()); wr.WriteEndAttribute(); wr.WriteStartAttribute("updated"); wr.WriteValue(questionary.Updated.ToString()); wr.WriteEndAttribute(); wr.WriteStartAttribute("template"); wr.WriteValue(questionary.TemplateId); wr.WriteEndAttribute(); wr.WriteStartElement("Questions"); WriteQuestions(); wr.WriteEndElement(); wr.WriteEndElement(); wr.WriteEndDocument(); wr.Close(); }
// Use this for initialization void Start() { if (System.IO.File.Exists(configPath) == false) { Xml.XmlWriterSettings settings = new Xml.XmlWriterSettings(); settings.Indent = true; string levelsPath = "Assets/scenes/"; string[] loaderPath = System.IO.Directory.GetFiles(levelsPath); ConfigWriter cfgFile = ConfigWriter.Create(configPath, settings); cfgFile.WriteStartDocument(); cfgFile.WriteStartElement("Config"); cfgFile.WriteStartElement("Levels"); cfgFile.WriteAttributeString("LevelsPath", levelsPath.ToString()); foreach (string file in loaderPath) { if (file.EndsWith(".meta") == false) { cfgFile.WriteElementString("Map", file.Remove(0, levelsPath.Length).Remove(file.Length - (levelsPath.Length + 6)).ToString()); } } cfgFile.WriteEndElement(); cfgFile.WriteEndElement(); cfgFile.WriteEndDocument(); cfgFile.Flush(); cfgFile.Close(); } }
public static void Write(XmlWriter writer, Ticket pt) { var declarations = NamespaceDeclarations(pt); writer.WriteStartDocument(); var prefix = declarations.LookupPrefix(Psf.PrintTicket.NamespaceName); writer.WriteStartElement(prefix, Psf.PrintTicket.LocalName, Psf.PrintTicket.NamespaceName); writer.WriteAttributeString("version", "1"); foreach (var decl in declarations) { writer.WriteAttributeString("xmlns", decl.Prefix, null, decl.Uri.NamespaceName); } foreach (var f in pt.Features()) { Write(writer, f); } foreach (var p in pt.Properties()) { Write(writer, p); } foreach (var p in pt.Parameters()) { Write(writer, p); } writer.WriteEndElement(); writer.Flush(); }
/// <summary>Serialize the <c>XmlRpcResponse</c> to the output stream.</summary> /// <param name="output">An <c>XmlTextWriter</c> stream to write data to.</param> /// <param name="obj">An <c>Object</c> to serialize.</param> /// <seealso cref="XmlRpcResponse"/> override public void Serialize(XmlWriter 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 void SaveRecentExperimentListToXML(RecentExperimentList pList, string pFilepath) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.CloseOutput = true; settings.CheckCharacters = true; // Create file using (System.Xml.XmlWriter writer = XmlWriter.Create(pFilepath, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("RecentExperiments"); foreach (var item in pList) { writer.WriteStartElement("RecentExperimentItem"); writer.WriteAttributeString("FullPath", item.FullPath); //writer.WriteAttributeString("Filename", item.Filename); writer.WriteAttributeString("LastAccessTime", item.LastAccessTime.ToString()); writer.WriteEndElement(); // RecentExperimentItem } writer.WriteEndElement(); // RecentExperiments writer.WriteEndDocument(); writer.Close(); } }
public void WriteResponseMessage ( XmlWriter writer, string innerXml, NuxleusAsyncResult asyncResult ) { using (writer) { writer.WriteStartDocument(); if (m_responseType == ResponseType.REDIRECT) { writer.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='/service/transform/openid-redirect.xsl'"); } writer.WriteStartElement("auth"); writer.WriteAttributeString("xml:base", "http://dev.amp.fm/"); writer.WriteAttributeString("status", m_status); if (m_responseType == ResponseType.REDIRECT) { writer.WriteElementString("url", "http://dev.amp.fm/"); } if (m_responseType == ResponseType.QUERY_RESPONSE && innerXml != null) { writer.WriteStartElement("response"); writer.WriteRaw(innerXml); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); } asyncResult.CompleteCall(); }
public EpochXMLPersistor(XmlWriter xw, Func<Guid> guidGenerator) : base(guidGenerator) { this.writer = xw; writer.WriteStartDocument(); writer.WriteStartElement(RootElementName); writer.WriteAttributeString("version", Version.ToString()); }
/// <summary> /// Decode an AMF packet into an AMFX format. /// </summary> /// <exception cref="FormatException">Error during decoding.</exception> public void Decode(Stream stream, XmlWriter output) { if (stream == null) throw new ArgumentNullException("stream"); if (!stream.CanRead) throw new ArgumentException(Errors.AmfPacketReader_Read_StreamClosed, "stream"); if (output == null) throw new ArgumentNullException("output"); try { var amfStreamReader = new AmfStreamReader(stream); var version = ReadPacketVersion(amfStreamReader); var decoder = CreateDecoder(version, _options); output.WriteStartDocument(); output.WriteStartElement(AmfxContent.AmfxDocument, AmfxContent.Namespace); output.WriteAttributeString(AmfxContent.VersionAttribute, version.ToAmfxName()); output.Flush(); //Read headers var headerCount = ReadDataCount(amfStreamReader); for (var i = 0; i < headerCount; i++) { var header = decoder.ReadPacketHeader(stream); output.WriteStartElement(AmfxContent.PacketHeader); output.WriteAttributeString(AmfxContent.PacketHeaderName, header.Name); output.WriteAttributeString(AmfxContent.PacketHeaderMustUnderstand, header.MustUnderstand.ToString()); decoder.Decode(stream, output); output.WriteEndElement(); output.Flush(); } //Read messages var messageCount = ReadDataCount(amfStreamReader); for (var i = 0; i < messageCount; i++) { var body = decoder.ReadPacketBody(stream); output.WriteStartElement(AmfxContent.PacketBody); output.WriteAttributeString(AmfxContent.PacketBodyTarget, body.Target); output.WriteAttributeString(AmfxContent.PacketBodyResponse, body.Response); decoder.Decode(stream, output); output.WriteEndElement(); output.Flush(); } output.WriteEndElement(); output.WriteEndDocument(); output.Flush(); } catch (Exception e) { output.Flush(); throw new FormatException(Errors.AmfPacketReader_DecodingError, e); } }
public void WriteToXml(XmlWriter writer) { Trace.WriteLine("Writing to XML"); writer.WriteStartDocument(); ProcessReport(_report, writer); writer.WriteEndDocument(); writer.Flush(); }
public static void WriteSoapEnvelopeStart(XmlWriter writer, bool addXSINamespace) { writer.WriteStartDocument(); writer.WriteStartElement("s", "Envelope", UPnPConsts.NS_SOAP_ENVELOPE); if (addXSINamespace) writer.WriteAttributeString("xmlns", "xsi", null, UPnPConsts.NS_XSI); writer.WriteAttributeString("s", "encodingStyle", null, UPnPConsts.NS_SOAP_ENCODING); writer.WriteStartElement("Body", UPnPConsts.NS_SOAP_ENVELOPE); }
public override void Write(System.Xml.XmlWriter writer) { writer.WriteStartDocument(); writer.WriteDocType("plist", "-//Apple Computer//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null); writer.WriteStartElement("plist"); writer.WriteAttributeString("version", version); Root.Write(writer); writer.WriteEndDocument(); }
internal XmlExpressionDumper(Stream stream, Encoding encoding, bool indent) : base() { XmlWriterSettings settings = new XmlWriterSettings(); settings.CheckCharacters = false; settings.Indent = true; settings.Encoding = encoding; _writer = XmlWriter.Create(stream, settings); _writer.WriteStartDocument(true); }
public GpxWriter(Stream stream) { Writer_ = XmlWriter.Create(stream, new XmlWriterSettings { CloseOutput = true, Indent = true }); Writer_.WriteStartDocument(false); Writer_.WriteStartElement("gpx", GPX_NAMESPACE); Writer_.WriteAttributeString("version", GPX_VERSION); Writer_.WriteAttributeString("creator", GPX_CREATOR); Writer_.WriteAttributeString("xmlns", GARMIN_EXTENSIONS_PREFIX, null, GARMIN_EXTENSIONS_NAMESPACE); }
public static void WriteXmlWriter (object value, XmlWriter writer) { writer.WriteStartDocument(); writer.WriteDocType("plist", "-//Apple Computer//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null); writer.WriteStartElement("plist"); writer.WriteAttributeString("version", "1.0"); new Plist().Compose(value, writer); writer.WriteEndElement(); writer.WriteEndDocument(); }
public void Write(XmlWriter writer) { writer.WriteStartDocument(); writer.WriteStartElement("Macro"); writer.WriteAttributeString("Name", "Custom tool"); WriteInputs(writer); WriteResults(writer); writer.WriteEndElement(); writer.WriteEndDocument(); }
public XmlLogger(ISimpleLogSettings log, StreamWriter w) : base(log) { _writer = new XmlTextWriter(w); _writer.WriteStartDocument(); _writer.WriteStartElement("terminal-log"); //接続時のアトリビュートを書き込む _writer.WriteAttributeString("time", DateTime.Now.ToString()); _buffer = new char[1]; }
public XmlWriterSerializer(XmlWriter xmlWriter, bool writeDocument) { _xmlWriter = xmlWriter; _writeDocument = writeDocument; if (writeDocument) { xmlWriter.WriteStartDocument(); } }
private void generateXml(XmlWriter writer) { writer.WriteStartDocument(); writer.WriteStartElement("results"); foreach (var runner in _results.GroupBy(x => x.Runner)) { writer.WriteStartElement("runner"); writer.WriteAttributeString("id", runner.Key); foreach (var assembly in runner.GroupBy(x => x.Assembly)) { writer.WriteStartElement("assembly"); writer.WriteAttributeString("name", assembly.Key); foreach (var fixture in assembly.GroupBy(x => x.TestFixture)) { writer.WriteStartElement("fixture"); writer.WriteAttributeString("name", fixture.Key); foreach (var test in fixture) { writer.WriteStartElement("test"); writer.WriteAttributeString("state", test.State.ToString()); writer.WriteAttributeString("name", test.TestName); if (test.TestDisplayName != null) writer.WriteAttributeString("displayName", test.TestDisplayName); writer.WriteAttributeString("duration", test.DurationInMilliseconds.ToString()); writer.WriteStartElement("message"); writer.WriteCData(test.Message); writer.WriteEndElement(); if (test.State == TestState.Failed || test.State == TestState.Ignored) { writer.WriteStartElement("stack-trace"); foreach (var line in test.StackLines) { writer.WriteStartElement("line"); writer.WriteStartElement("method"); writer.WriteCData(line.Method); writer.WriteEndElement(); writer.WriteStartElement("file"); writer.WriteAttributeString("line", line.Line.ToString()); writer.WriteRaw(line.File); writer.WriteEndElement(); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); }
public static void WriteXml(XmlWriter writer, Action writeGraph, string version = CurrentVersion) { writer.WriteStartDocument(); writer.WriteStartElement(ElementName, Namespace); writer.WriteAttributeString(VersionAttributeName, version); writeGraph(); writer.WriteEndElement(); writer.WriteEndDocument(); }
/// <summary> /// Starts the process of creating debug XML during decoding. /// This method is called by the GifComponent constructor if the supplied /// xmlDebugging parameter is set to true. /// Sets the private member _xmlDebugging to true. /// Creates a new XmlWriter with an underlying MemoryStream and writes /// a start element to it, named after the derived type. /// </summary> private void WriteDebugXmlStart() { _xmlDebugging = true; XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; _debugXmlStream = new MemoryStream(); _debugXmlWriter = XmlWriter.Create(_debugXmlStream, settings); _debugXmlWriter.WriteStartDocument(); WriteDebugXmlStartElement(this.GetType().Name); }
public bool startDocument(string version = DefaultXmlVersion, string encoding = null, string standalone = null) { if (version != DefaultXmlVersion) { PhpException.ArgumentValueNotSupported(nameof(version), version); } if (encoding != null && !string.Equals(encoding, "utf-8", StringComparison.CurrentCultureIgnoreCase)) { PhpException.ArgumentValueNotSupported(nameof(encoding), encoding); } if (string.IsNullOrEmpty(standalone)) { return(CheckedCall(() => _writer.WriteStartDocument())); } else { return(CheckedCall(() => _writer.WriteStartDocument(standalone == "yes"))); } }
public LogFile(string fileName) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = System.Text.Encoding.UTF8; logStream = XmlWriter.Create(fileName, settings); logStream.WriteStartDocument(); logStream.WriteStartElement("LogEntries"); DateTime dt = DateTime.Now; logStream.WriteElementString("Date", dt.ToString("D")); logStream.WriteElementString("Time", dt.ToString("T")); }
private void PrepareXmlFile(string fileName) { XmlWriterSettings xws = new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8, Indent = true }; _xw = System.Xml.XmlWriter.Create(fileName, xws); _xw.WriteStartDocument(); _xw.WriteStartElement(string.IsNullOrEmpty(_settings.CustomRootNode) ? "dataroot" : XmlConvert.EncodeLocalName(_settings.CustomRootNode)); }
void Init(Control root, StreamWriter destination) { m_output = new XmlTextWriter(destination); AttachTo(root); m_output.WriteStartDocument(true); m_output.WriteStartElement("instructions"); Application.AddMessageFilter(this); if (root is Form) { (root as Form).Closed += new EventHandler(ScriptMaker_Closed); } }
/// <summary> /// Saves links to an XML file. /// </summary> /// <param name="filepath">The path of the XML file.</param> private static void SaveLinksToXML(string filepath, List <WebsiteLink> pVideos, List <WebsiteLink> pLinks) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.CloseOutput = true; settings.CheckCharacters = true; // Create file using (System.Xml.XmlWriter writer = XmlWriter.Create(filepath, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("OnlineContent"); writer.WriteStartElement("Videos"); if (pVideos != null) { foreach (var item in pVideos) { writer.WriteStartElement("VideoItem"); writer.WriteAttributeString("Title", item.Title); writer.WriteAttributeString("Description", item.Description); writer.WriteAttributeString("URL", item.LinkURL); writer.WriteEndElement(); // VideoItem } } writer.WriteEndElement(); // Videos writer.WriteStartElement("Links"); if (pLinks != null) { foreach (var item in pLinks) { writer.WriteStartElement("LinkItem"); writer.WriteAttributeString("Title", item.Title); writer.WriteAttributeString("Description", item.Description); writer.WriteAttributeString("URL", item.LinkURL); writer.WriteEndElement(); // LinkItem } } writer.WriteEndElement(); // Links writer.WriteEndElement(); // StartPage writer.WriteEndDocument(); writer.Close(); } }
// This method creates Xml with a point and returns it in a string form public string ToXml() { //Initiate XML stuff KeyValuePair <string, string> point = GetNewPoint(); string lon = point.Key; string lat = point.Value; StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings); writer.WriteStartDocument(); writer.WriteStartElement("Point"); writer.WriteElementString("lon", lon); writer.WriteElementString("lat", lat); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); return(sb.ToString()); }
private string CreateEmptyXml() { var settings = new XmlWriterSettings { OmitXmlDeclaration = false, Encoding = Encoding.UTF8 }; var stream = new MemoryStream(); using (System.Xml.XmlWriter writer = XmlWriter.Create(stream, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("feed"); writer.WriteEndElement(); writer.Flush(); writer.Close(); } stream.Position = 0; var streamReader = new StreamReader(stream); return(streamReader.ReadToEnd()); }
/// <summary> /// Exports an answer matrix to XML format /// </summary> /// <param name="answerSet">Answer matrix</param> /// <param name="sourceId">ID of source artifacts</param> /// <param name="targetId">ID of target artifacts</param> /// <param name="outputPath">Output file path</param> public static void ExportXML(TLSimilarityMatrix answerSet, string sourceId, string targetId, string outputPath) { if (answerSet == null) { throw new TraceLabSDK.ComponentException("Received null answer similarity matrix"); } System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.CloseOutput = true; settings.CheckCharacters = true; //create file using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(outputPath, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("answer_set"); WriteAnswerSetXMLInfo(writer, sourceId, targetId); WriteXMLLinks(answerSet, writer); writer.WriteEndElement(); //answer_set writer.WriteEndDocument(); writer.Close(); } //System.Diagnostics.Trace.WriteLine("File created , you can find the file " + outputPath); }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 execute_Utilities = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter; IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter); IGPValue outputOSMFileGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber)); // get the name of the feature dataset int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\"); string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; System.Xml.XmlWriter xmlWriter = null; try { xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings); } catch (Exception ex) { message.AddError(120021, ex.Message); return; } xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("osm"); // start the osm root node xmlWriter.WriteAttributeString("version", "0.6"); // add the version attribute xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute // write all the nodes // use a feature search cursor to loop through all the known points and write them out as osm node IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer; if (osmFeatureClasses == null) { message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name)); return; } IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt"); if (osmPointFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt")); return; } // check the extension of the point feature class to determine its version int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion(); IFeatureCursor searchCursor = null; System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsEmpty.Add("", ""); message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg")); int pointCounter = 0; string nodesExportedMessage = String.Empty; // collect the indices for the point feature class once int pointOSMIDFieldIndex = osmPointFeatureClass.Fields.FindField("OSMID"); int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset"); int pointVersionFieldIndex = osmPointFeatureClass.Fields.FindField("osmversion"); int pointUIDFieldIndex = osmPointFeatureClass.Fields.FindField("osmuid"); int pointUserFieldIndex = osmPointFeatureClass.Fields.FindField("osmuser"); int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp"); int pointVisibleFieldIndex = osmPointFeatureClass.Fields.FindField("osmvisible"); int pointTagsFieldIndex = osmPointFeatureClass.Fields.FindField("osmTags"); using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPointFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node)); IFeature currentFeature = searchCursor.NextFeature(); IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == true) { // convert the found point feature into a osm node representation to store into the OSM XML file node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion); pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty); // increase the point counter to later status report pointCounter++; currentFeature = searchCursor.NextFeature(); } else { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loader so far nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); return; } } } nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); // next loop through the line and polygon feature classes to export those features as ways // in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln"); if (osmLineFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln")); return; } message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg")); // as we are looping through the line and polygon feature classes let's collect the multi-part features separately // as they are considered relations in the OSM world List<relation> multiPartElements = new List<relation>(); System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way)); int lineCounter = 0; int relationCounter = 0; string waysExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmLineFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int lineOSMIDFieldIndex = osmLineFeatureClass.Fields.FindField("OSMID"); int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset"); int lineVersionFieldIndex = osmLineFeatureClass.Fields.FindField("osmversion"); int lineUIDFieldIndex = osmLineFeatureClass.Fields.FindField("osmuid"); int lineUserFieldIndex = osmLineFeatureClass.Fields.FindField("osmuser"); int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp"); int lineVisibleFieldIndex = osmLineFeatureClass.Fields.FindField("osmvisible"); int lineTagsFieldIndex = osmLineFeatureClass.Fields.FindField("osmTags"); int lineMembersFieldIndex = osmLineFeatureClass.Fields.FindField("osmMembers"); IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } IFeatureClass osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply"); IFeatureWorkspace commonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace; if (osmPolygonFeatureClass == null) { message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply")); return; } using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPolygonFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int polygonOSMIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("OSMID"); int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset"); int polygonVersionFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmversion"); int polygonUIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuid"); int polygonUserFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuser"); int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp"); int polygonVisibleFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmvisible"); int polygonTagsFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmTags"); int polygonMembersFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); // now let's go through the relation table message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg")); ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation"); if (relationTable == null) { message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation")); return; } System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation)); string relationsExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { ICursor rowCursor = relationTable.Search(null, false); comReleaser.ManageLifetime(rowCursor); IRow currentRow = rowCursor.NextRow(); // collect the indices for the relation table once int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID"); int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset"); int relationVersionFieldIndex = relationTable.Fields.FindField("osmversion"); int relationUIDFieldIndex = relationTable.Fields.FindField("osmuid"); int relationUserFieldIndex = relationTable.Fields.FindField("osmuser"); int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp"); int relationVisibleFieldIndex = relationTable.Fields.FindField("osmvisible"); int relationTagsFieldIndex = relationTable.Fields.FindField("osmTags"); int relationMembersFieldIndex = relationTable.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentRow != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion); relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty); // increase the line counter for later status report relationCounter++; currentRow = rowCursor.NextRow(); } } // lastly let's serialize the collected multipart-geometries back into relation elements foreach (relation currentRelation in multiPartElements) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); return; } relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty); relationCounter++; } relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document } catch (Exception ex) { message.AddError(11111, ex.StackTrace); message.AddError(120026, ex.Message); } }
public override void WriteStartDocument() { CheckAsync(); coreWriter.WriteStartDocument(); }
public override void WriteStartDocument() { _wrapped.WriteStartDocument(); }
private void click_Move(object sender, RoutedEventArgs e) { pp.IsOpen = false; List <DB.Halls> Halls = (List <DB.Halls>)lv.ItemsSource; if (((System.Windows.Controls.Button)sender).Tag + "" == "0") { FolderBrowserDialog fbd = new FolderBrowserDialog(); string Path = ""; fbd.Description = "Выберите папку для записи файла."; if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { Path = fbd.SelectedPath; } else { pp.IsOpen = true; return; } switch (cbxFormat.SelectedIndex) { case 0: { List <string> strList = new List <string>(); foreach (var i in Halls) { strList.Add(i.ID + "" + ';' + i.Square + "" + ';' + i.Windows + ';' + i.Heating + ';' + i.Target + ';' + i.DepartmentID + ';' + i.BuildingID + ';' + i.ChiefID); } File.WriteAllLines(Path + @"\Exsport.csv", strList); break; } case 1: { System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(Path + @"\Exsport.xml"); writer.WriteStartDocument(); writer.WriteStartElement("Halls"); foreach (var i in Halls) { writer.WriteStartElement("Hall"); writer.WriteElementString("ID", i.ID + ""); writer.WriteElementString("Square", i.Square + ""); writer.WriteElementString("Windows", i.Windows + ""); writer.WriteElementString("Heating", i.Heating + ""); writer.WriteElementString("Target", i.Target); writer.WriteElementString("Department", i.DepartmentID + ""); writer.WriteElementString("Building", i.BuildingID + ""); writer.WriteElementString("Chief", i.ChiefID + ""); writer.WriteEndElement(); writer.Flush(); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); break; } case 2: { string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Extended properties=Excel 8.0; User ID=;Password=;Data Source = " + Path + @"\Exsport.xls"; OleDbConnection conn = new OleDbConnection(connectionString); conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.CommandText = "CREATE TABLE [Halls] (ID VARCHAR, Square VARCHAR, Windows VARCHAR, Heating VARCHAR, Target VARCHAR, DepartmentID VARCHAR, BuildingID VARCHAR, ChiefID VARCHAR);"; cmd.ExecuteNonQuery(); foreach (var i in Halls) { cmd.CommandText = "INSERT INTO [Halls] (ID,Square,Windows,Heating,Target,DepartmentID,BuildingID,ChiefID) values ('" + i.ID + "', '" + i.Square + "', '" + i.Windows + "', '" + i.Heating + "', '" + i.Target + "', '" + i.DepartmentID + "', '" + i.BuildingID + "', '" + i.ChiefID + "')"; cmd.ExecuteNonQuery(); } conn.Close(); break; } case 3: { string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Extended properties=Excel 8.0; User ID=;Password=;Data Source = " + Path + @"\Exsport.xlsx"; OleDbConnection conn = new OleDbConnection(connectionString); conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.CommandText = "CREATE TABLE [Halls] (ID VARCHAR, Square VARCHAR, Windows VARCHAR, Heating VARCHAR, Target VARCHAR, DepartmentID VARCHAR, BuildingID VARCHAR, ChiefID VARCHAR);"; cmd.ExecuteNonQuery(); foreach (var i in Halls) { cmd.CommandText = "INSERT INTO [Halls] (ID,Square,Windows,Heating,Target,DepartmentID,BuildingID,ChiefID) values ('" + i.ID + "', '" + i.Square + "', '" + i.Windows + "', '" + i.Heating + "', '" + i.Target + "', '" + i.DepartmentID + "', '" + i.BuildingID + "', '" + i.ChiefID + "';"; cmd.ExecuteNonQuery(); } conn.Close(); break; } } System.Windows.MessageBox.Show("Экспорт совершён!", "Perfect", MessageBoxButton.OK, MessageBoxImage.Information); } else { switch (cbxFormat.SelectedIndex) { case 0: { if (System.Windows.MessageBox.Show("Для удачной записи файл должен быть следующего формата: |Square|Windows|Heating|Target|DepartmentID|BuildingID|ChiefID|. Продолжить? ", "Caution", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No) { pp.IsOpen = true; return; } OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "CSV|*.csv;"; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { pp.IsOpen = true; return; } var csv = File.ReadAllLines(ofd.FileName); int GoodCount = 0; int BadCount = 0; try { foreach (var i in csv) { var str = i.Split(';'); db.Halls.Add(new DB.Halls { Square = double.Parse(str[0]), Windows = int.Parse(str[1]), Heating = int.Parse(str[2]), Target = str[3], DepartmentID = int.Parse(str[4]), BuildingID = int.Parse(str[5]), ChiefID = int.Parse(str[6]) }); } db.SaveChanges(); GoodCount++; } catch { BadCount++; } string Message = ""; if (BadCount == 0) { Message = "Импорт прошёл успешно!"; } else if (GoodCount != 0) { Message = "Импорт прошёл с некоторыми ошибками!"; } else { Message = "Импорт не прошёл из-за появившихся ошибок!"; } System.Windows.MessageBox.Show(Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information); break; } case 1: { if (System.Windows.MessageBox.Show("Для удачной записи в файле не должно быть поле 'ID'. Продолжить? ", "Caution", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No) { pp.IsOpen = true; return; } OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "XML|*.xml;"; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { pp.IsOpen = true; return; } int GoodCount = 0; int BadCount = 0; XmlDocument doc = new XmlDocument(); doc.Load(ofd.FileName); foreach (XmlNode i in doc.DocumentElement) { try { DB.Halls hall = new DB.Halls(); hall.ID = int.Parse(i["ID"].InnerText); hall.Square = double.Parse(i["Square"].InnerText); hall.Windows = int.Parse(i["Windows"].InnerText); hall.Heating = int.Parse(i["Heating"].InnerText); hall.Target = i["Target"].InnerText; hall.DepartmentID = int.Parse(i["Department"].InnerText); hall.BuildingID = HelpClasses.StaticClass.SelectBuilding.Kadastr; hall.ChiefID = int.Parse(i["Chief"].InnerText); db.Halls.Add(hall); db.SaveChanges(); GoodCount++; } catch { BadCount++; } } string Message = ""; if (BadCount == 0) { Message = "Импорт прошёл успешно!"; } else if (GoodCount != 0) { Message = "Импорт прошёл с некоторыми ошибками!"; } else { Message = "Импорт не прошёл из-за появившихся ошибок!"; } System.Windows.MessageBox.Show(Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information); break; } case 2: { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "XLS|*.xls;"; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { pp.IsOpen = true; return; } DataSet ds = new DataSet(); string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Extended properties=Excel 8.0; User ID=;Password=;Data Source = " + ofd.FileName; OleDbConnection conn = new OleDbConnection(connectionString); conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; DataTable dtHalls = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); foreach (DataRow dr in dtHalls.Rows) { string hallName = dr["TABLE_NAME"].ToString(); if (!hallName.EndsWith("$")) { continue; } cmd.CommandText = "SELECT * FROM [" + hallName + "]"; DataTable dt = new DataTable(); dt.TableName = hallName; OleDbDataAdapter da = new OleDbDataAdapter(); da.Fill(dt); ds.Tables.Add(dt); } cmd = null; conn.Close(); break; } } click_Sort(null, null); } }
public override void WriteStartDocument(bool standalone) { writer.WriteStartDocument(standalone); }
public override void WriteStartDocument() { _writer.WriteStartDocument(); }
// We could use async Read from SQLite and async XML writing, but there is no performance gain, I tested that. // Going async actually introduces the problem of ExportComplete firing too early, // but you will only notice that with huge exports. internal void Serialize(string fileName) { /* We are going to perform a series of queries: * One for the primary category * and then then one for every connection. * * A number of observations: * If we ever were to allow nested connections, we would need some recursion algorithm. * In the current setup, we only process the child relations of the primary table */ // collect some information before the dataread to prevent unnecessary calls var subQueries = _primaryTable.ChildRelations.Cast <DataRelation>().Select(s => new ChildTableQuery( // no checks if keys exist s.ChildTable.ExtendedProperties[DataSetHelper.LinkTableSelectCommandTextExtProp].ToString(), JsonConvert.DeserializeObject <CommenceConnection>(s.ExtendedProperties[DataSetHelper.CommenceConnectionDescriptionExtProp].ToString())) ).ToArray(); using (var connection = new SQLiteConnection(_cs)) { connection.Open(); using (var transaction = connection.BeginTransaction()) { using (var command = new SQLiteCommand(connection)) { command.Connection = connection; command.CommandText = SQLiteWriter.GetSQLiteSelectQueryForTable(_primaryTable); // start reading data using (var reader = command.ExecuteReader()) { XmlWriterSettings xmlSettings = new XmlWriterSettings { Async = false, WriteEndDocumentOnClose = true, Indent = true, Encoding = Encoding.UTF8 // this is what SQLite uses }; using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(fileName, xmlSettings)) { writer.WriteStartDocument(); writer.WriteStartElement(string.IsNullOrEmpty(_settings.CustomRootNode) ? XmlConvert.EncodeLocalName(_primaryTable.TableName) : XmlConvert.EncodeLocalName(_settings.CustomRootNode)); writer.WriteStartElement("Items"); bool includeThids = ((ExportSettings)_settings).UserRequestedThids; while (reader.Read()) { writer.WriteStartElement(null, "Item", null); WriteNodes(reader, writer, includeThids); // next step is to get the connected values // we use a separate query for that // that is probably way too convoluted // we should probably stick to using a more intelligent reader. // the problem is that we need to make sense of the lines that // the reader returns. The XmlWriter is forward only, // so botching together the nodes that belong together is a problem. // we could just use a fully filled dataset? What about size limitations? Performance? SQLiteCommand sqCmd = new SQLiteCommand(connection); foreach (var q in subQueries) { sqCmd.CommandText = q.CommandText; sqCmd.Transaction = transaction; sqCmd.Parameters.AddWithValue("@id", reader.GetInt64(0)); // fragile var subreader = sqCmd.ExecuteReader(); while (subreader.Read()) { if (_settings.NestConnectedItems) { WriteNestedNodes(subreader, writer, q.Connection, includeThids); } else { WriteNodes(subreader, writer, includeThids); } } // while rdr.Read sqCmd.Reset(); // make ready for next use } // foreach subqueries writer.WriteEndElement(); } // while } // xmlwriter } // reader } // cmd transaction.Commit(); } // transaction } // con } // method
public void writeFeatureXML() { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineChars = "\r\n"; System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create("C:\\major\\ProjectedPatterns.xml", settings); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("Pattens"); /* * for(int u=1;u<=5;u++) * { * xmlWriter.WriteElementString("TotalPatterns"+u, Convert.ToString(5)); * } * xmlWriter.WriteElementString("TotalPatterns11", Convert.ToString(5)); * * int[] patOfFace = new int[10]; * try * { * Bitmap faceToProject = (Bitmap)Image.FromFile("C:\\major\\knownfaces\\1.jpg"); * FaceRecognition.searchDetected_ic(faceToProject); * int[] patttt = FaceRecognition.getEudPat(); * for (int u = 1; u <= 10; u++) * { * xmlWriter.WriteElementString("TotalPatterns" + u, Convert.ToString(patttt[u - 1])); * } * } * * catch (Exception ex) * { * MessageBox.Show(ex.Message); * } */ //--------------------------------Known----------------------------- string faceFileLocationKnown = "C:\\major\\knownfaces\\"; xmlWriter.WriteStartElement("KnownPatterns"); for (int j = 1; j <= noOfKnownPatterns; j++) { string wrtStr = "KnownPattern" + Convert.ToString(j); xmlWriter.WriteStartElement(wrtStr); Bitmap faceToProject = (Bitmap)Image.FromFile(faceFileLocationKnown + "k" + j + ".jpg"); //*********This will return first 10 minimum euclidian distances of the face stored in faceToProject**** FaceRecognition.searchDetected_ic(faceToProject); int[] patOfFace = FaceRecognition.getEudPat(); //********* //double[,] projectedFeatureRLDA = FaceRecognition.getRLdaFeatures(faceToProject); //for (int i = 0; i < projectedFeatureRLDA.GetLength(0); i++) //for (int i = 0; i < netSizeVCT; i++)//netSizeVCT is no of element in each pattern for (int i = 0; i < netSizeVCT; i++)//netSizeVCT is no of element in each pattern { string s3 = "KnownPatternElement" + i; string feature = Convert.ToString(patOfFace[i]); xmlWriter.WriteElementString(s3, feature); } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); //--------------------------------------------------------------------- //--------------------------------Unknown----------------------------- string faceFileLocationUnknown = "C:\\major\\unknownfaces\\"; xmlWriter.WriteStartElement("UnknownPatterns"); for (int j = 1; j <= noOfUnknownPatterns; j++) { string wrtStr = "UnknownPattern" + Convert.ToString(j); xmlWriter.WriteStartElement(wrtStr); Bitmap faceToProject = (Bitmap)Image.FromFile(faceFileLocationUnknown + "NiD (" + j + ").jpg"); //*********This will return first 10 minimum euclidian distances of the face stored in faceToProject**** FaceRecognition.searchDetected_ic(faceToProject); int[] patOfFace = FaceRecognition.getEudPat(); //********* //double[,] projectedFeatureRLDA = FaceRecognition.getRLdaFeatures(faceToProject); //for (int i = 0; i < projectedFeatureRLDA.GetLength(0); i++) for (int i = 0; i < netSizeVCT; i++) { string s3 = "UnknownPatternElement" + i; string feature = Convert.ToString(patOfFace[i]); xmlWriter.WriteElementString(s3, feature); } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); //--------------------------------------------------------------------- xmlWriter.WriteEndElement(); xmlWriter.Close(); }
public QueryOutputWriterV1(XmlWriter writer, XmlWriterSettings settings) { _wrapped = writer; _systemId = settings.DocTypeSystem; _publicId = settings.DocTypePublic; if (settings.OutputMethod == XmlOutputMethod.Xml) { bool documentConformance = false; // Xml output method shouldn't output doc-type-decl if system ID is not defined (even if public ID is) // Only check for well-formed document if output method is xml if (_systemId != null) { documentConformance = true; _outputDocType = true; } // Check for well-formed document if standalone="yes" in an auto-generated xml declaration if (settings.Standalone == XmlStandalone.Yes) { documentConformance = true; } if (documentConformance) { if (settings.Standalone == XmlStandalone.Yes) { _wrapped.WriteStartDocument(true); } else { _wrapped.WriteStartDocument(); } } if (settings.CDataSectionElements != null && settings.CDataSectionElements.Count > 0) { _bitsCData = new BitStack(); _lookupCDataElems = new Dictionary <XmlQualifiedName, XmlQualifiedName>(); _qnameCData = new XmlQualifiedName(); // Add each element name to the lookup table foreach (XmlQualifiedName name in settings.CDataSectionElements) { _lookupCDataElems[name] = null; } _bitsCData.PushBit(false); } } else if (settings.OutputMethod == XmlOutputMethod.Html) { // Html output method should output doc-type-decl if system ID or public ID is defined if (_systemId != null || _publicId != null) { _outputDocType = true; } } }