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 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(); }
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(); } }
// 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 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(); }
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; }
// *************************************************************************** // Beendet an zu schreiben public static void EndXML(XmlWriter writer) { writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); writer.Close(); }
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(); }
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(); }
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(); } }
// 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()); }
// 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 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(); }
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 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 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(); }
public void Write(XmlWriter writer) { writer.WriteStartDocument(); writer.WriteStartElement("Macro"); writer.WriteAttributeString("Name", "Custom tool"); WriteInputs(writer); WriteResults(writer); writer.WriteEndElement(); writer.WriteEndDocument(); }
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> /// Finishes off writing the debug XML. /// </summary> protected void WriteDebugXmlFinish() { if (_xmlDebugging) { _debugXmlWriter.WriteRaw(Environment.NewLine); _debugXmlWriter.WriteEndElement(); _debugXmlWriter.WriteEndDocument(); _debugXmlWriter.Flush(); _debugXmlWriter.Close(); } }
private static void FinalizeXslStylesheet(XmlWriter writer) { writer.WriteEndElement(); // xsl:for-each writer.WriteEndElement(); // xsl-template writer.WriteEndElement(); // xsl:stylesheet writer.WriteEndDocument(); }
// 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.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(); } else { if (colorsDictionary.Count > 0) { return; } //load colors ConfigReader cfgFile = new ConfigReader(); cfgFile.Load(configPath); Xml.XmlNodeList colorNodes = cfgFile.GetElementsByTagName("Color"); foreach (Xml.XmlElement nodes in colorNodes) { colorsDictionary.Add(nodes.GetAttribute("colorName"), new string[] { nodes.GetAttribute("one"), nodes.GetAttribute("two"), nodes.GetAttribute("three"), nodes.GetAttribute("four") }); } } //Debug.Log ( "config says hello"); }
private void Write(XmlWriter writer) { writer.WriteStartDocument(); XElement root = new XElement(Xmlns + "Image", new XAttribute("TileSize", AllTileDefaults.DziTileSize), new XAttribute("Overlap", _dziTileOverlap), new XAttribute("Format", AllTileDefaults.DziTileFormat), new XElement(Xmlns + "Size", new XAttribute("Width", _size.Width), new XAttribute("Height", _size.Height))); root.WriteTo(writer); writer.WriteEndDocument(); }
public void Write(XmlWriter writer) { writer.WriteStartDocument(); writer.WriteStartElement("netreflector"); try { WriteTypes(writer); } finally { writer.WriteEndDocument(); } }
protected override void Render(XmlWriter reportBuilder) { reportBuilder.WriteStartDocument(); reportBuilder.WriteStartElement("testsuites"); foreach (var contextByAssembly in ContextsByAssembly) { Render(reportBuilder, contextByAssembly.Key, contextByAssembly.Value); } reportBuilder.WriteEndElement(); reportBuilder.WriteEndDocument(); }
/// <summary> /// Serializes an XML-RPC response to a <see cref="System.Xml.XmlWriter"/>. /// </summary> /// <param name="writer">the <see cref="System.Xml.XmlWriter"/> to write</param> /// <param name="response">the <see cref="LX.EasyWeb.XmlRpc.IXmlRpcResponse"/> to serialize</param> /// <param name="config">the context configuration</param> /// <param name="typeSerializerFactory">the <see cref="LX.EasyWeb.XmlRpc.Serializer.ITypeSerializerFactory"/> to get type serializers</param> /// <exception cref="System.Xml.XmlException">failed writing the response XML</exception> public void WriteResponse(XmlWriter writer, IXmlRpcResponse response, IXmlRpcStreamRequestConfig config, ITypeSerializerFactory typeSerializerFactory) { writer.WriteStartDocument(); writer.WriteStartElement(XmlRpcSpec.METHOD_RESPONSE_TAG); if (response.Fault == null) RecursiveTypeSerializer.WriteParams(writer, config, typeSerializerFactory, response.Result); else WriteFaultResponse(writer, response.Fault, config, typeSerializerFactory); writer.WriteEndElement(); writer.WriteEndDocument(); }
private static void WriteDictionary(ILocalizationDictionary dictionary, XmlWriter writer) { writer.WriteStartDocument(); var typedDictionary = dictionary as LocalizationDictionary; if(typedDictionary!=null) { WriteIncludes(typedDictionary, writer); } writer.WriteStartElement("dictionary"); foreach(var key in dictionary.Keys) { WriteKey(key, dictionary, writer); } writer.WriteEndElement(); writer.WriteEndDocument(); }
protected internal void CloseXmlFile() { try { // write closing elements and close XMLWriter _xw.WriteEndElement(); _xw.WriteEndDocument(); } finally { _xw.Flush(); _xw.Close(); } }
private void Write(XmlWriter writer) { try { _w = writer; _w.WriteStartDocument(); WriteCollectionElement(); _w.WriteEndDocument(); } catch (Exception ex) { ex.GetType(); } }
public void Write( XmlWriter writer) { writer.WriteStartElement("PdbxFile"); writer.WriteStartElement("Assembly"); WriteTokensPair(writer, _context.AssemblyDefinition.MetadataToken.ToUInt32(), 0x00000000); writer.WriteElementString("FileName", _context.AssemblyDefinition.MainModule.Name); WriteVersionInfo(writer, _context.AssemblyDefinition.Name.Version); writer.WriteStartElement("Classes"); _context.TypeDefinitionTable.ForEachItems((token, item) => WriteClassInfo(writer, token, item)); writer.WriteEndDocument(); }
public void generate(CommonTree ast, XmlWriter writer) { try { writer.WriteStartDocument(); writeXMLNode(ast, writer); writer.WriteEndDocument(); writer.Close(); } catch (Exception e) { Console.WriteLine("Error while translating AST: " + e.Message); } }
/// <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(); } }
public void WriteLevel(XmlWriter writer) { writer.WriteStartDocument(); foreach (Level level in this.lstLevel.Items) level.ToXML(writer); writer.WriteStartElement("physics"); foreach (Item p in this.lstPhysics.Items) p.ToXML(writer); writer.WriteEndElement(); writer.WriteStartElement("actors"); foreach (Item p in this.lstActors.Items) p.ToXML(writer); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); }
public void SaveToFile(XmlWriter writer) { writer.WriteStartDocument(); writer.WriteStartElement("ParticleSystem"); writer.WriteStartAttribute("Name"); writer.WriteValue(name); writer.WriteEndAttribute(); foreach (ParticleEffect effect in effects) { effect.SaveToFile(writer); } writer.WriteEndElement(); /* Finish the document out */ writer.WriteEndDocument(); }
// 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()); }
public bool endDocument() { while (_state.Count != 0) // Closes all open sections. { switch (_state.Peek()) { case State.Comment: endComment(); break; case State.PI: endPi(); break; case State.CDATA: endCdata(); break; case State.DTD: endDtd(); break; case State.DtdElement: endDtdElement(); break; case State.DtdEntity: endDtdEntity(); break; case State.DtdAttlist: endDtdAttlist(); break; default: return(false); } } return(CheckedCall(() => _writer.WriteEndDocument())); }
public void CreateXMLDoc(String filePath) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; settings.NewLineChars = "\n"; //settings.OmitXmlDeclaration = true; // "<?xml version="1.0" encoding="utf-8"?>" //writer = new XmlTextWriter(filePath, Encoding.Unicode); writer = XmlWriter.Create(filePath,settings); writer.WriteStartDocument(); writer.WriteStartElement("map"); // //writer.WriteStartElement("name"); //Writing name of the mode writer.WriteStartElement("mode"); writer.WriteAttributeString("name", mode.mode.ToString()); //writer.WriteAttributeString("name", mode.getName()); writer.WriteEndElement(); //Writing map structure block writer.WriteStartElement("structure"); // //MapObject[][] tempMapObject = map.GetInternalForm(); foreach (MapObject[] m in map.MapInstance) { for (int j = 0; j < m.Length; j++) { writer.WriteStartElement("element"); writer.WriteAttributeString("x", m[j].X.ToString()); writer.WriteAttributeString("y", m[j].Y.ToString()); writer.WriteAttributeString("type", m[j].Type.ToString()); writer.WriteEndElement(); } } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); }
protected override void WriteTestMetadata(XmlWriter writer, IEnumerable<MSTest> tests, string assemblyFilePath) { writer.WriteStartDocument(); writer.WriteStartElement("TestLists", @"http://microsoft.com/schemas/VisualStudio/TeamTest/2006"); writer.WriteStartElement("TestList"); writer.WriteAttributeString("name", "Lists of Tests"); writer.WriteAttributeString("id", RootTestListGuid.ToString()); writer.WriteEndElement(); writer.WriteStartElement("TestList"); writer.WriteAttributeString("id", SelectedTestListGuid.ToString()); writer.WriteAttributeString("name", SelectedTestListName); writer.WriteAttributeString("parentListId", RootTestListGuid.ToString()); writer.WriteStartElement("TestLinks"); foreach (MSTest test in tests) { if (test.IsTestCase) { writer.WriteStartElement("TestLink"); writer.WriteAttributeString("id", test.Guid.ToString()); writer.WriteAttributeString("name", test.TestName); writer.WriteAttributeString("storage", assemblyFilePath); writer.WriteAttributeString("type", "Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestElement, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.ObjectModel, PublicKeyToken=b03f5f7f11d50a3a"); writer.WriteEndElement(); } } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); }
public void Write(XmlWriter w, vCard c) { if (c.Fn.Items.Count == 0) throw new ArgumentException("vCard must have non-empty FN property", "FN"); w.WriteStartDocument(); w.WriteStartElement("vcards", vCard.vcard40NS); w.WriteAttributeString("xmlns", "", null, vCard.vcard40NS); w.WriteStartElement("vcard"); if (c.Source.Default != null) WriteUriElement(w, "source", c.Source.Default.Value.ToString()); if (c.Name != null) WriteTextElement(w, "name", c.Name); WriteTextElement(w, "fn", c.Fn.Default.Value); //WriteTextElement(w, "email", c.EMail); if (c.N != null && (!string.IsNullOrEmpty(c.N.FamilyName) || !string.IsNullOrEmpty(c.N.GivenNames))) { w.WriteStartElement("n"); if (c.N.FamilyName != null) WriteTextElement(w, "surname", c.N.FamilyName); if (c.N.GivenNames != null) WriteTextElement(w, "given", c.N.GivenNames); w.WriteEndElement(); } foreach (vCard.PropertyRegistration reg in c.PropertyRegistrations) { reg.Property.WriteXml(w, reg.PropertyName, reg.PropertyNS); } w.WriteEndElement(); // vcard w.WriteEndElement(); // vcards w.WriteEndDocument(); }
/// <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 override string Index(string folderPath) { FolderInfo folderInfo = GetFolderInfo(folderPath); folderInfo.Update(); XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Encoding = new UTF8Encoding(false); xmlWriterSettings.ConformanceLevel = ConformanceLevel.Document; xmlWriterSettings.Indent = true; using (MemoryStream ms = new MemoryStream()) { using (xmlWriter = XmlWriter.Create(ms, xmlWriterSettings)) { xmlWriter.WriteStartDocument(); IndexFolder(folderInfo); xmlWriter.WriteEndDocument(); xmlWriter.Flush(); } return Encoding.UTF8.GetString(ms.ToArray()); } }
private void WriteClientBinXml(XmlWriter writer) { // Setup initial conditions. writer.WriteStartDocument(); writer.WriteStartElement("ClientBin"); // Enumerate the collection of XAP files. var folder = new DirectoryInfo(Server.MapPath("ClientBin")); foreach (var file in folder.GetFiles("*.xap")) { var kb = Math.Round(Decimal.Divide(file.Length, 1000), 2); writer.WriteStartElement("File"); writer.WriteAttributeString("Extension", "xap"); writer.WriteAttributeString("Kb", kb.ToString()); writer.WriteString(file.Name.TrimEnd(".xap".ToCharArray())); writer.WriteEndElement(); // File. } // Finish up. writer.WriteEndElement(); // ClientBin. writer.WriteEndDocument(); writer.Close(); }
internal void WriteTo( XmlWriter xmlWriter ) { Debug.Assert( _xmlDiff._fragments != TriStateBool.DontKnown ); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement( XmlDiff.Prefix, "xmldiff", XmlDiff.NamespaceUri ); xmlWriter.WriteAttributeString( "version", "1.0" ); xmlWriter.WriteAttributeString( "srcDocHash", _xmlDiff._sourceDoc.HashValue.ToString() ); xmlWriter.WriteAttributeString( "options", _xmlDiff.GetXmlDiffOptionsString() ); xmlWriter.WriteAttributeString( "fragments", ( _xmlDiff._fragments == TriStateBool.Yes ) ? "yes" : "no" ) ; WriteChildrenTo( xmlWriter, _xmlDiff ); OperationDescriptor curOD = _descriptors; while ( curOD != null ) { curOD.WriteTo( xmlWriter ); curOD = curOD._nextDescriptor; } xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); }
internal static void WriteProjectXml( XmlWriter writer, string projectPath, string sourcePath, string filters, string startupFile, bool excludeNodeModules, out Guid projectGuid ) { var projectHome = CommonUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(projectPath), sourcePath); projectGuid = Guid.NewGuid(); writer.WriteStartDocument(); writer.WriteStartElement("Project", "http://schemas.microsoft.com/developer/msbuild/2003"); writer.WriteAttributeString("DefaultTargets", "Build"); writer.WriteStartElement("PropertyGroup"); writer.WriteStartElement("Configuration"); writer.WriteAttributeString("Condition", " '$(Configuration)' == '' "); writer.WriteString("Debug"); writer.WriteEndElement(); writer.WriteElementString("SchemaVersion", "2.0"); writer.WriteElementString("ProjectGuid", projectGuid.ToString("B")); writer.WriteElementString("ProjectHome", projectHome); writer.WriteElementString("ProjectView", "ShowAllFiles"); if (CommonUtils.IsValidPath(startupFile)) { writer.WriteElementString("StartupFile", Path.GetFileName(startupFile)); } else { writer.WriteElementString("StartupFile", String.Empty); } writer.WriteElementString("WorkingDirectory", "."); writer.WriteElementString("OutputPath", "."); writer.WriteElementString("ProjectTypeGuids", "{3AF33F2E-1136-4D97-BBB7-1795711AC8B8};{349c5851-65df-11da-9384-00065b846f21};{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}"); bool typeScriptSupport = EnumerateAllFiles(sourcePath, filters, excludeNodeModules) .Any(filename => NodejsConstants.TypeScriptExtension.Equals(Path.GetExtension(filename), StringComparison.OrdinalIgnoreCase)); if (typeScriptSupport) { writer.WriteElementString("TypeScriptSourceMap", "true"); writer.WriteElementString("TypeScriptModuleKind", "CommonJS"); writer.WriteElementString("EnableTypeScript", "true"); } writer.WriteStartElement("VisualStudioVersion"); writer.WriteAttributeString("Condition", "'$(VisualStudioVersion)' == ''"); writer.WriteString("14.0"); writer.WriteEndElement(); writer.WriteStartElement("VSToolsPath"); writer.WriteAttributeString("Condition", "'$(VSToolsPath)' == ''"); writer.WriteString(@"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)"); writer.WriteEndElement(); writer.WriteEndElement(); // </PropertyGroup> // VS requires property groups with conditions for Debug // and Release configurations or many COMExceptions are // thrown. writer.WriteStartElement("PropertyGroup"); writer.WriteAttributeString("Condition", "'$(Configuration)' == 'Debug'"); writer.WriteEndElement(); writer.WriteStartElement("PropertyGroup"); writer.WriteAttributeString("Condition", "'$(Configuration)' == 'Release'"); writer.WriteEndElement(); var folders = new HashSet<string>( Directory.EnumerateDirectories(sourcePath, "*", SearchOption.AllDirectories) .Select(dirName => CommonUtils.TrimEndSeparator( CommonUtils.GetRelativeDirectoryPath(sourcePath, dirName) ) ) .Where(ShouldIncludeDirectory) ); // Exclude node_modules and bower_components folders. if (excludeNodeModules) { folders.RemoveWhere(NodejsConstants.ContainsNodeModulesOrBowerComponentsFolder); } writer.WriteStartElement("ItemGroup"); foreach (var file in EnumerateAllFiles(sourcePath, filters, excludeNodeModules)) { var ext = Path.GetExtension(file); if (NodejsConstants.JavaScriptExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) { writer.WriteStartElement("Compile"); } else if (NodejsConstants.TypeScriptExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) { writer.WriteStartElement("TypeScriptCompile"); } else { writer.WriteStartElement("Content"); } writer.WriteAttributeString("Include", file); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("ItemGroup"); foreach (var folder in folders.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s)) { writer.WriteStartElement("Folder"); writer.WriteAttributeString("Include", folder); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("Import"); writer.WriteAttributeString("Project", @"$(MSBuildToolsPath)\Microsoft.Common.targets"); writer.WriteAttributeString("Condition", @"Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"); writer.WriteEndElement(); writer.WriteComment("Do not delete the following Import Project. While this appears to do nothing it is a marker for setting TypeScript properties before our import that depends on them."); writer.WriteStartElement("Import"); writer.WriteAttributeString("Project", @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets"); writer.WriteAttributeString("Condition", @"False"); writer.WriteEndElement(); writer.WriteStartElement("Import"); writer.WriteAttributeString("Project", @"$(VSToolsPath)\Node.js Tools\Microsoft.NodejsTools.targets"); writer.WriteEndElement(); writer.WriteRaw(@" <ProjectExtensions> <VisualStudio> <FlavorProperties GUID=""{349c5851-65df-11da-9384-00065b846f21}""> <WebProjectProperties> <UseIIS>False</UseIIS> <AutoAssignPort>True</AutoAssignPort> <DevelopmentServerPort>0</DevelopmentServerPort> <DevelopmentServerVPath>/</DevelopmentServerVPath> <IISUrl>http://localhost:48022/</IISUrl> <NTLMAuthentication>False</NTLMAuthentication> <UseCustomServer>True</UseCustomServer> <CustomServerUrl>http://localhost:1337</CustomServerUrl> <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile> </WebProjectProperties> </FlavorProperties> <FlavorProperties GUID=""{349c5851-65df-11da-9384-00065b846f21}"" User=""""> <WebProjectProperties> <StartPageUrl> </StartPageUrl> <StartAction>CurrentPage</StartAction> <AspNetDebugging>True</AspNetDebugging> <SilverlightDebugging>False</SilverlightDebugging> <NativeDebugging>False</NativeDebugging> <SQLDebugging>False</SQLDebugging> <ExternalProgram> </ExternalProgram> <StartExternalURL> </StartExternalURL> <StartCmdLineArguments> </StartCmdLineArguments> <StartWorkingDirectory> </StartWorkingDirectory> <EnableENC>False</EnableENC> <AlwaysStartWebServerOnDebug>False</AlwaysStartWebServerOnDebug> </WebProjectProperties> </FlavorProperties> </VisualStudio> </ProjectExtensions> "); writer.WriteEndElement(); // </Project> writer.WriteEndDocument(); }
public void Write(XbimModel model, XmlWriter output) { try { _written = new HashSet<long>(); output.WriteStartDocument(); output.WriteStartElement("ex", "iso_10303_28", _iso10303urn); output.WriteAttributeString("version", "2.0"); output.WriteAttributeString("xmlns", "xsi", null, _xsi); output.WriteAttributeString("xmlns", "xlink", null, _xlink); output.WriteAttributeString("xmlns", "ex", null, _iso10303urn); output.WriteAttributeString("xsi", "schemaLocation", null, string.Format("{0} {1}", _iso10303urn, _exXSD)); _fileHeader = model.Header; WriteISOHeader(output); //Write out the uos output.WriteStartElement("uos", _namespace); output.WriteAttributeString("id", "uos_1"); output.WriteAttributeString("description", "Xbim IfcXml Export"); output.WriteAttributeString("configuration", "i_ifc2x3"); output.WriteAttributeString("edo", ""); output.WriteAttributeString("xmlns", "ex", null, _iso10303urn); output.WriteAttributeString("xmlns", "ifc", null, _namespace); output.WriteAttributeString("xsi", "schemaLocation", null, string.Format("{0} {1}", _namespace, _ifcXSD)); foreach (var item in model.InstanceHandles) { Write(model, item.EntityLabel, output); } output.WriteEndElement(); //uos output.WriteEndElement(); //iso_10303_28 output.WriteEndDocument(); } catch (Exception e) { throw new Exception("Failed to write IfcXml file", e); } finally { _written = null; } }
void Write(Drawing drawing, XmlWriter writer) { var figures = drawing.GetSerializableFigures(); writer.WriteStartDocument(); writer.WriteStartElement("Drawing"); writer.WriteAttributeDouble("Version", drawing.Version); writer.WriteAttributeString("Creator", System.Windows.Application.Current.ToString()); WriteCoordinateSystem(drawing, writer); WriteStyles(drawing, writer); WriteFigureList(figures, writer); writer.WriteEndElement(); writer.WriteEndDocument(); }
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 WriteEndDocument() { _wrapped.WriteEndDocument(); }
public static void CloseWriter(System.Xml.XmlWriter writer) { writer.WriteEndElement(); writer.WriteEndDocument(); writer.Dispose(); }
public override void WriteEndDocument() { CheckAsync(); _coreWriter.WriteEndDocument(); }
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 WriteEndDocument() { writer.WriteEndDocument(); }