public static void CreateXml(string path) { XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8) { Formatting = Formatting.Indented }; writer.WriteStartDocument(); writer.WriteStartElement("root"); for (int i = 0; i < 5; i++) { writer.WriteStartElement("Node"); writer.WriteAttributeString("Text", "这是文章内容!~!!~~"); writer.WriteAttributeString("ImageUrl", ""); writer.WriteAttributeString("NavigateUrl", "Url..." + i.ToString()); writer.WriteAttributeString("Expand", "true"); for (int j = 0; j < 5; j++) { writer.WriteStartElement("Node"); writer.WriteAttributeString("Text", "......名称"); writer.WriteAttributeString("NavigateUrl", "Url..." + i.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteFullEndElement(); writer.Close(); }
public void WriteXml(XmlTextWriter xmlWriter) { xmlWriter.WriteStartElement("module"); xmlWriter.WriteAttributeString("name", testModule.Text); if (testModule.Trainer) { xmlWriter.WriteAttributeString("type", "training"); } else { xmlWriter.WriteAttributeString("type", "test"); } // Если ид не был прочитан при загрузке проекта. if (testModule.Id.Equals(Guid.Empty)) { testModule.Id = Guid.NewGuid(); } xmlWriter.WriteAttributeString("id", "#module{" + testModule.Id.ToString().ToUpper() + "}"); xmlWriter.WriteAttributeString("order", testModule.QuestionSequence.ToString().ToLower()); xmlWriter.WriteAttributeString("errlimit", testModule.MistakesNumber.ToString()); xmlWriter.WriteAttributeString("time", testModule.TimeRestriction.ToString()); if (testModule.TestType.Equals(Enums.TestType.InTest)) { xmlWriter.WriteAttributeString("io", "i"); } else if (testModule.TestType.Equals(Enums.TestType.OutTest)) { xmlWriter.WriteAttributeString("io", "o"); } #region Группы foreach (var g in testModule.Groups) { g.XmlWriter.WriteXml(xmlWriter); } #endregion #region Вопросы foreach (var q in testModule.Questions) { q.XmlWriter.WriteXml(xmlWriter); } #endregion xmlWriter.WriteFullEndElement(); }
public override void WriteXml(XmlTextWriter xmlWriter) { var q = question as OuterQuestion; xmlWriter.WriteStartElement("question"); xmlWriter.WriteAttributeString("name", q.Text); xmlWriter.WriteAttributeString("id", "#module{" + q.Id.ToString().ToUpper() + "}"); if (q.NextQuestion != null) { xmlWriter.WriteAttributeString("next_question", "#module{" + q.NextQuestion.Id.ToString().ToUpper() + "}"); } xmlWriter.WriteAttributeString("type", "outer"); xmlWriter.WriteAttributeString("time", q.TimeRestriction.ToString()); #region Wsdl xmlWriter.WriteStartElement("wsdl"); xmlWriter.WriteAttributeString("address", q.Url); xmlWriter.WriteAttributeString("testid", q.TestId); xmlWriter.WriteEndElement(); #endregion #region Task xmlWriter.WriteStartElement("task"); xmlWriter.WriteAttributeString("id", q.TaskId); xmlWriter.WriteAttributeString("name", q.TaskName); xmlWriter.WriteAttributeString("subject", q.SubjectName); xmlWriter.WriteAttributeString("testname", q.TestName); xmlWriter.WriteStartElement("declaration"); xmlWriter.WriteCData(q.DocumentHtml); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); #endregion if (!(question.Parent is Group)) { xmlWriter.WriteStartElement("mark"); xmlWriter.WriteAttributeString("value", q.Marks.ToString()); if (question.Profile != null) { xmlWriter.WriteAttributeString("concept_id", "#elem{" + question.Profile.Id.ToString().ToUpper() + "}"); } xmlWriter.WriteFullEndElement(); } xmlWriter.WriteEndElement(); }
public override void ProcessRequest(string request, ref Socket socket, bool authenticated, string body) { QueryString query = new QueryString(request); String sMimeType = "text/xml"; string data=""; string id = query.GetValues("id")[0]; int hash = 0; try { hash = Convert.ToInt32(id); if (Earth3d.ImagesetHashTable.ContainsKey(hash)) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (XmlTextWriter xmlWriter = new XmlTextWriter( sw )) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlWriter.WriteStartElement("Folder"); IImageSet imageset = (IImageSet)Earth3d.ImagesetHashTable[hash]; string alternateUrl = ""; try { if (File.Exists(imageset.Url)) { alternateUrl = string.Format("http://{0}:5050/imageset/{1}/{2}", MyWebServer.IpAddress, hash, Path.GetFileName(imageset.Url)); } } catch { } ImageSetHelper.SaveToXml(xmlWriter, imageset, alternateUrl); xmlWriter.WriteFullEndElement(); xmlWriter.Close(); } data = sb.ToString(); } } catch { } SendHeaderAndData(data, ref socket, sMimeType); }
public void WriteXml(XmlTextWriter xmlWriter) { xmlWriter.WriteStartElement("group"); xmlWriter.WriteAttributeString("count", group.ChosenQuestionsCount.ToString()); xmlWriter.WriteAttributeString("name", group.Text); #region Вопросы foreach (var q in group.Questions) { q.XmlWriter.WriteXml(xmlWriter); } #endregion xmlWriter.WriteStartElement("mark"); xmlWriter.WriteAttributeString("value", group.Marks.ToString()); if (group.Profile != null) { xmlWriter.WriteAttributeString("concept_id", "#elem{" + group.Profile.Id.ToString().ToUpper() + "}"); } xmlWriter.WriteFullEndElement(); xmlWriter.WriteFullEndElement(); }
public static void CreatXml(string XmlFileName) { try { System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(XmlFileName, System.Text.Encoding.GetEncoding("utf-8")); writer.Formatting = System.Xml.Formatting.Indented; writer.WriteRaw("<System Parameter Save>"); writer.WriteStartElement("Config"); //writer.WriteEndElement() writer.WriteFullEndElement(); writer.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } }
public void WriteXml(XmlTextWriter xmlWriter) { foreach (var idc in trainingModule.InConceptParent.InDummyConcepts) { xmlWriter.WriteStartElement("input"); xmlWriter.WriteAttributeString("concept_id", "#elem{" + idc.Concept.Id.ToString().ToUpper() + "}"); xmlWriter.WriteEndElement(); } foreach (var odc in trainingModule.OutConceptParent.OutDummyConcepts) { xmlWriter.WriteStartElement("output"); xmlWriter.WriteAttributeString("concept_id", "#elem{" + odc.Concept.Id.ToString().ToUpper() + "}"); xmlWriter.WriteEndElement(); } xmlWriter.WriteStartElement("html_text"); xmlWriter.WriteAttributeString("id", "{" + Guid.NewGuid().ToString().ToUpper() + "}"); xmlWriter.WriteCData(HtmlToXml(trainingModule)); xmlWriter.WriteFullEndElement(); }
// Writes the current node into the provided XmlWriter. private void WriteNode(XmlTextWriter xtw, bool defattr) { int d = this.NodeType == XmlNodeType.None ? -1 : this.Depth; while (this.Read() && (d < this.Depth)) { switch (this.NodeType) { case XmlNodeType.Element: xtw.WriteStartElement(this.Prefix, this.LocalName, this.NamespaceURI); xtw.QuoteChar = this.QuoteChar; xtw.WriteAttributes(this, defattr); if (this.IsEmptyElement) { xtw.WriteEndElement(); } break; case XmlNodeType.Text: xtw.WriteString(this.Value); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: xtw.WriteWhitespace(this.Value); break; case XmlNodeType.CDATA: xtw.WriteCData(this.Value); break; case XmlNodeType.EntityReference: xtw.WriteEntityRef(this.Name); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: xtw.WriteProcessingInstruction(this.Name, this.Value); break; case XmlNodeType.DocumentType: xtw.WriteDocType(this.Name, this.GetAttribute("PUBLIC"), this.GetAttribute("SYSTEM"), this.Value); break; case XmlNodeType.Comment: xtw.WriteComment(this.Value); break; case XmlNodeType.EndElement: xtw.WriteFullEndElement(); break; } } if (d == this.Depth && this.NodeType == XmlNodeType.EndElement) { Read(); } }
void saveHighScores() { XmlTextWriter writer = new XmlTextWriter("Content\\highscores.xml", null); writer.Formatting = Formatting.Indented; writer.WriteRaw("<root>"); foreach (HighScore element in highscores) { writer.WriteStartElement("item"); writer.WriteElementString("name", element.name); writer.WriteElementString("score", element.score.ToString()); writer.WriteFullEndElement(); } writer.WriteRaw("\n</root>"); writer.Close(); }
//************************************************************************* // Method: EnumerateCheckAndSaveFaults // // Description: Uses Reflection to enumerate all Faults in each specified category // and checks to see if they are enabled, if so, they are saved. // Parameters: // categoryName - the category name for which to enumerate and check faults // xwriter - reference to an existing XmlTextWriter object which is used to write // // Return Value: none //************************************************************************* private void EnumerateCheckAndSaveFaults(String categoryName, ref XmlTextWriter xwriter, ProcessMdiWindow window) { foreach (PropertyInfo pi in window.GetType().GetProperties()) { if (pi.Name.StartsWith ("Inject" + categoryName)) { bool IsFaultInjected = (bool) window.GetType().InvokeMember (pi.Name, BindingFlags.GetProperty, null, window, null); if (IsFaultInjected) { xwriter.WriteStartElement (categoryName + "Fault"); xwriter.WriteAttributeString ("Name", pi.Name.Replace("Inject" + categoryName, "")); xwriter.WriteFullEndElement (); } } } }
/// <summary> /// Metodo responsavel em escrever o XML VersoesWSDLs.xml na pasta do executavel /// </summary> /// <author> /// Renan Borges - 25/06/2013 /// </author> /// <param name="ListArquivosGerar">Lista com os informacoes a serem gravados pertinentes aos arquivos</param> private void EscreverXmlWSDLs(List<ArquivoItem> ListArquivosGerar) { if (ListArquivosGerar.Count > 0) { XmlTextWriter arqXML = new XmlTextWriter(XMLVersoesWSDL, Encoding.UTF8); arqXML.WriteStartDocument(); arqXML.Formatting = Formatting.Indented; arqXML.WriteStartElement("arquivos"); foreach (ArquivoItem item in ListArquivosGerar) { arqXML.WriteStartElement("wsdl"); arqXML.WriteElementString("arquivo", item.Arquivo); arqXML.WriteElementString("data", item.Data.ToShortDateString()); arqXML.WriteElementString("manual", item.Manual.ToString()); arqXML.WriteEndElement(); } arqXML.WriteFullEndElement(); arqXML.Close(); } }
internal void WriteTourXML(string outFile) { using (var xmlWriter = new XmlTextWriter(outFile, Encoding.UTF8)) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlWriter.WriteStartElement("Tour"); xmlWriter.WriteAttributeString("ID", id); xmlWriter.WriteAttributeString("Title", title); xmlWriter.WriteAttributeString("Descirption", Description); xmlWriter.WriteAttributeString("Description", Description); xmlWriter.WriteAttributeString("RunTime", RunTime.TotalSeconds.ToString()); xmlWriter.WriteAttributeString("Author", author); xmlWriter.WriteAttributeString("AuthorEmail", authorEmail); xmlWriter.WriteAttributeString("OrganizationUrl", organizationUrl); xmlWriter.WriteAttributeString("OrganizationName", OrgName); xmlWriter.WriteAttributeString("Keywords", Keywords); xmlWriter.WriteAttributeString("UserLevel", level.ToString()); xmlWriter.WriteAttributeString("Classification", type.ToString()); xmlWriter.WriteAttributeString("Taxonomy", taxonomy); xmlWriter.WriteAttributeString("DomeMode", DomeMode.ToString()); var timeLineTour = IsTimelineTour(); xmlWriter.WriteAttributeString("TimeLineTour", timeLineTour.ToString()); if (timeLineTour) { xmlWriter.WriteStartElement("TimeLineTourStops"); foreach (var stop in TourStops) { stop.SaveToXml(xmlWriter, true); } xmlWriter.WriteEndElement(); xmlWriter.WriteRaw(Resources.UpdateRequired); } else { xmlWriter.WriteStartElement("TourStops"); foreach (var stop in TourStops) { stop.SaveToXml(xmlWriter, true); } xmlWriter.WriteEndElement(); } var masterList = CreateLayerMasterList(); // This will now save and sync emtpy frames... var referencedFrames = GetReferenceFrameList(); xmlWriter.WriteStartElement("ReferenceFrames"); foreach (var item in referencedFrames) { item.SaveToXml(xmlWriter); } xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("Layers"); foreach (var t in masterList) { if (LayerManager.LayerList.ContainsKey(t)) { LayerManager.LayerList[t].SaveToXml(xmlWriter); } } xmlWriter.WriteEndElement(); xmlWriter.WriteFullEndElement(); xmlWriter.Close(); } }
private static void WriteModules(CourseItem ci, XmlTextWriter xw) { for (var i = 0; i < ci.Nodes.Count; i++) { if (ci.Nodes[i] is TrainingModule) { #region Запись учебных модулей var tm = ci.Nodes[i] as TrainingModule; xw.WriteStartElement("module"); xw.WriteAttributeString("name", tm.Text); xw.WriteAttributeString("type", "text"); xw.WriteAttributeString("id", "#module{" + tm.Id.ToString().ToUpper() + "}"); tm.XmlWriter.WriteXml(xw); RibbonStatusStripEx.Instance.MakeProgressStep(0); System.Windows.Forms.Application.DoEvents(); if (tm.Nodes.Count != 0) { WriteModules(tm, xw); } xw.WriteFullEndElement(); #endregion } else if (ci.Nodes[i] is TestModule) { #region Запись контролей var tm = ci.Nodes[i] as TestModule; tm.XmlWriter.WriteXml(xw); #endregion RibbonStatusStripEx.Instance.MakeProgressStep(0); System.Windows.Forms.Application.DoEvents(); } } }
// // Outputs XML documentation comment from tokenized comments. // public bool OutputDocComment (string asmfilename, string xmlFileName) { XmlTextWriter w = null; try { w = new XmlTextWriter (xmlFileName, null); w.Indentation = 4; w.Formatting = Formatting.Indented; w.WriteStartDocument (); w.WriteStartElement ("doc"); w.WriteStartElement ("assembly"); w.WriteStartElement ("name"); w.WriteString (Path.GetFileNameWithoutExtension (asmfilename)); w.WriteEndElement (); // name w.WriteEndElement (); // assembly w.WriteStartElement ("members"); XmlCommentOutput = w; module.GenerateDocComment (this); w.WriteFullEndElement (); // members w.WriteEndElement (); w.WriteWhitespace (Environment.NewLine); w.WriteEndDocument (); return true; } catch (Exception ex) { Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", xmlFileName, ex.Message); return false; } finally { if (w != null) w.Close (); } }
/// <summary> /// Converts the specified html into XHTML compliant text. /// </summary> /// <param name="reader">sgml reader.</param> /// <param name="html">html to convert.</param> /// <param name="converter">The converter.</param> /// <returns></returns> /// /// private static string ConvertHtmlToXHtml(SgmlReader reader, string html, Converter<string, string> converter) { reader.DocType = "html"; reader.WhitespaceHandling = WhitespaceHandling.All; // Hack to fix SF bug #1678030 html = RemoveNewLineBeforeCDATA(html); reader.InputStream = new StringReader("<html>" + html + "</html>"); reader.CaseFolding = CaseFolding.ToLower; StringWriter writer = new StringWriter(); XmlWriter xmlWriter = null; try { xmlWriter = new XmlTextWriter(writer); bool insideAnchor = false; bool skipRead = false; while ((skipRead || reader.Read()) && !reader.EOF) { skipRead = false; switch(reader.NodeType) { case XmlNodeType.Element: //Special case for anchor tags for the time being. //We need some way to communicate which elements the current node is nested within if (reader.IsEmptyElement) { xmlWriter.WriteStartElement(reader.LocalName); xmlWriter.WriteAttributes(reader, true); if (reader.LocalName == "a" || reader.LocalName == "script") xmlWriter.WriteFullEndElement(); else xmlWriter.WriteEndElement(); } else { if (reader.LocalName == "a") insideAnchor = true; xmlWriter.WriteStartElement(reader.LocalName); xmlWriter.WriteAttributes(reader, true); } break; case XmlNodeType.Text: string text = reader.Value; if (converter != null && !insideAnchor) xmlWriter.WriteRaw(converter(text)); else xmlWriter.WriteString(text); break; case XmlNodeType.EndElement: if (reader.LocalName == "a") insideAnchor = false; if (reader.LocalName == "a" || reader.LocalName == "script") xmlWriter.WriteFullEndElement(); else xmlWriter.WriteEndElement(); break; default: xmlWriter.WriteNode(reader, true); skipRead = true; break; } } } finally { if (xmlWriter != null) { xmlWriter.Close(); } } string xml = writer.ToString(); return xml.Substring("<html>".Length, xml.Length - "<html></html>".Length); }
/// <summary> /// Запись файла манифеста. /// </summary> /// <param name="questionFiles">список вопросов теста</param> /// <remarks>Используется в экспорте теста в формате IMS QTI.</remarks> private void WriteManifestFile(string path) { XmlTextWriter imsManifestWriter = new XmlTextWriter(path + "imsmanifest.xml", null); // форматирование файла imsManifestWriter.Formatting = Formatting.Indented; // создание файла imsmanifest.xml imsManifestWriter.WriteStartDocument(); imsManifestWriter.WriteStartElement("manifest"); imsManifestWriter.WriteAttributeString("xmlns", @"http://www.imsglobal.org/xsd/imscp_v1p1"); imsManifestWriter.WriteAttributeString("xmlns:imsmd", @"http://www.imsglobal.org/xsd/imsmd_v1p2"); imsManifestWriter.WriteAttributeString("xmlns:xsi", @"http://www.w3.org/2001/XMLSchema-instance"); imsManifestWriter.WriteAttributeString("xmlns:imsqti", @"http://www.imsglobal.org/xsd/imsqti_v2p1"); imsManifestWriter.WriteAttributeString("identifier", "MANIFEST-" + System.Guid.NewGuid().ToString()); imsManifestWriter.WriteAttributeString("xsi:schemaLocation", @"http://www.imsglobal.org/xsd/imscp_v1p1" + @"http://www.imsglobal.org/xsd/imscp_v1p2.xsd" + @"http://www.imsglobal.org/xsd/imsmd_v1p2" + @"http://www.imsglobal.org/xsd/imsmd_v1p2p4.xsd" + @"http://www.imsglobal.org/xsd/imsqti_v2p1" + @"http://www.imsglobal.org/xsd/imsqti_v2p1.xsd"); imsManifestWriter.WriteStartElement("metadata"); imsManifestWriter.WriteElementString("schema", "IMS Content"); imsManifestWriter.WriteElementString("schemaVersion", "1.2"); imsManifestWriter.WriteStartElement("imsmd:lom"); imsManifestWriter.WriteStartElement("imsmd:general"); imsManifestWriter.WriteStartElement("imsmd:title"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString("Упаковка IMS QTI"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:title imsManifestWriter.WriteElementString("imsmd:language", "ru"); imsManifestWriter.WriteStartElement("imsmd:description"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString("Эта упаковка содержит файл теста и файлы вопросов"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:description imsManifestWriter.WriteFullEndElement(); // imsmd:general imsManifestWriter.WriteStartElement("imsmd:lifecycle"); imsManifestWriter.WriteStartElement("imsmd:version"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString("1.0"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:version imsManifestWriter.WriteStartElement("imsmd:status"); imsManifestWriter.WriteStartElement("imsmd:source"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString("LOMv1.0"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:source imsManifestWriter.WriteStartElement("imsmd:value"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "x-none"); imsManifestWriter.WriteString("Final"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:value imsManifestWriter.WriteFullEndElement(); // imsmd:status imsManifestWriter.WriteFullEndElement(); // imsmd:lifecycle imsManifestWriter.WriteStartElement("imsmd:metametadata"); imsManifestWriter.WriteElementString("imsmd:metadatascheme", "LOMv1.0"); imsManifestWriter.WriteElementString("imsmd:metadatascheme", "QTIv2.1"); imsManifestWriter.WriteElementString("imsmd:language", "en"); imsManifestWriter.WriteFullEndElement(); // imsmd:metametadata imsManifestWriter.WriteStartElement("imsmd:technical"); imsManifestWriter.WriteElementString("imsmd:format", "text/x-imsqti-test-xml"); imsManifestWriter.WriteElementString("imsmd:format", "text/x-imsqti-item-xml"); imsManifestWriter.WriteElementString("imsmd:format", "image/png"); imsManifestWriter.WriteElementString("imsmd:format", "image/jpeg"); imsManifestWriter.WriteElementString("imsmd:format", "image/bmp"); imsManifestWriter.WriteElementString("imsmd:format", "image/gif"); imsManifestWriter.WriteFullEndElement(); // imsmd:technical imsManifestWriter.WriteStartElement("imsmd:rights"); imsManifestWriter.WriteStartElement("imsmd:description"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "en"); imsManifestWriter.WriteString("(c) 2005 - 2008, IMS Global Learning Consortium; Visual Editor"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:description imsManifestWriter.WriteFullEndElement(); // imsmd:rights imsManifestWriter.WriteFullEndElement(); // imsmd:lom imsManifestWriter.WriteFullEndElement(); // metadata imsManifestWriter.WriteStartElement("organizations"); imsManifestWriter.WriteFullEndElement(); // organizations imsManifestWriter.WriteStartElement("resources"); //файл теста imsManifestWriter.WriteStartElement("resource"); imsManifestWriter.WriteAttributeString("identifier", "RES-" + Guid.NewGuid().ToString());//не уверена imsManifestWriter.WriteAttributeString("type", "imsqti_test_xmlv2p1"); imsManifestWriter.WriteAttributeString("href", FileName); imsManifestWriter.WriteStartElement("metadata"); imsManifestWriter.WriteStartElement("imsmd:lom"); imsManifestWriter.WriteStartElement("imsmd:general"); imsManifestWriter.WriteStartElement("imsmd:title"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString("Тест в формате IMS QTI"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:title imsManifestWriter.WriteElementString("imsmd:language", "ru"); imsManifestWriter.WriteStartElement("imsmd:description"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString("Это тест в формате IMS QTI"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:description imsManifestWriter.WriteFullEndElement(); // imsmd:general imsManifestWriter.WriteStartElement("imsmd:lifecycle"); imsManifestWriter.WriteStartElement("imsmd:version"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString("1.0"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:version imsManifestWriter.WriteStartElement("imsmd:status"); imsManifestWriter.WriteStartElement("imsmd:source"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString("LOMv1.0"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:source imsManifestWriter.WriteStartElement("imsmd:value"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "x-none"); imsManifestWriter.WriteString("Final"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:value imsManifestWriter.WriteFullEndElement(); // imsmd:status imsManifestWriter.WriteFullEndElement(); // imsmd:lifecycle imsManifestWriter.WriteStartElement("imsmd:metametadata"); imsManifestWriter.WriteElementString("imsmd:metadatascheme", "LOMv1.0"); imsManifestWriter.WriteElementString("imsmd:language", "en"); imsManifestWriter.WriteFullEndElement(); // imsmd:metametadata imsManifestWriter.WriteStartElement("imsmd:technical"); imsManifestWriter.WriteElementString("imsmd:format", "text/x-imsqti-test-xml"); imsManifestWriter.WriteFullEndElement(); // imsmd:technical imsManifestWriter.WriteStartElement("imsmd:rights"); imsManifestWriter.WriteStartElement("imsmd:description"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "en"); imsManifestWriter.WriteString("(c) 2005 - 2008, IMS Global Learning Consortium; Visual Editor"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:description imsManifestWriter.WriteFullEndElement(); // imsmd:rights imsManifestWriter.WriteFullEndElement(); // imsmd:lom imsManifestWriter.WriteFullEndElement(); // metadata imsManifestWriter.WriteStartElement("file"); imsManifestWriter.WriteAttributeString("href", fileName); imsManifestWriter.WriteFullEndElement(); // file foreach (Group group in groups) { foreach (Question question in group.Questions) { imsManifestWriter.WriteStartElement("dependency"); imsManifestWriter.WriteAttributeString("identifierref", "RES-" + question.Id.ToString());//guid меняю на Id наверное так imsManifestWriter.WriteFullEndElement(); // dependency } } foreach (Question question in questions) { imsManifestWriter.WriteStartElement("dependency"); imsManifestWriter.WriteAttributeString("identifierref", "RES-" + question.Id.ToString()); imsManifestWriter.WriteFullEndElement(); // dependency } imsManifestWriter.WriteFullEndElement(); // resource //~~~файл теста //---файлы вопросов foreach (Group group in groups) { foreach (Question question in group.Questions) { imsManifestWriter.WriteStartElement("resource"); imsManifestWriter.WriteAttributeString("identifier", "RES-" + question.Id.ToString()); imsManifestWriter.WriteAttributeString("type", "imsqti_item_xmlv2p1"); imsManifestWriter.WriteAttributeString("href", question.FileName); imsManifestWriter.WriteStartElement("metadata"); imsManifestWriter.WriteStartElement("imsmd:lom"); imsManifestWriter.WriteStartElement("imsmd:general"); imsManifestWriter.WriteElementString("imsmd:identifier", question.identifier); imsManifestWriter.WriteStartElement("imsmd:title"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString(question.Text); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:title imsManifestWriter.WriteElementString("imsmd:language", "ru"); imsManifestWriter.WriteStartElement("imsmd:description"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString(question.Description); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:description imsManifestWriter.WriteFullEndElement(); // imsmd:general imsManifestWriter.WriteStartElement("imsmd:lifecycle"); imsManifestWriter.WriteStartElement("imsmd:version"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString("1.0"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:version imsManifestWriter.WriteStartElement("imsmd:status"); imsManifestWriter.WriteStartElement("imsmd:source"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "x-none"); imsManifestWriter.WriteString("LOMv1.0"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:source imsManifestWriter.WriteStartElement("imsmd:value"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "x-none"); imsManifestWriter.WriteString("Draft"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:value imsManifestWriter.WriteFullEndElement(); // imsmd:status imsManifestWriter.WriteFullEndElement(); // imsmd:lifecycle imsManifestWriter.WriteStartElement("imsmd:technical"); imsManifestWriter.WriteElementString("imsmd:format", "text/x-imsqti-item-xml"); imsManifestWriter.WriteFullEndElement(); // imsmd:technical imsManifestWriter.WriteStartElement("imsmd:rights"); imsManifestWriter.WriteStartElement("imsmd:description"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "en"); imsManifestWriter.WriteString("(c) Visual Editor"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:description imsManifestWriter.WriteFullEndElement(); // imsmd:rights imsManifestWriter.WriteFullEndElement(); // imsmd:lom imsManifestWriter.WriteStartElement("imsmd:qtiMetadata"); imsManifestWriter.WriteElementString("imsmd:timeDependent", question.IsTimeDependent.ToString()); imsManifestWriter.WriteElementString("imsmd:interactionType", question.InteractionType.ToString()); if (question.IsAdaptive) { imsManifestWriter.WriteElementString("imsmd:feedbackType", "adaptive"); } else { imsManifestWriter.WriteElementString("imsmd:feedbackType", "none"); } imsManifestWriter.WriteElementString("imsmd:solutionAvailable", "true"); imsManifestWriter.WriteFullEndElement(); // imsmd:qtiMetadata imsManifestWriter.WriteFullEndElement(); // metadata imsManifestWriter.WriteStartElement("file"); imsManifestWriter.WriteAttributeString("href", question.FileName); imsManifestWriter.WriteFullEndElement(); // file foreach (string img in question.MmediaFiles) { imsManifestWriter.WriteStartElement("file"); imsManifestWriter.WriteAttributeString("href", "resources\\" + Path.GetFileName(img)); imsManifestWriter.WriteFullEndElement(); // file } imsManifestWriter.WriteFullEndElement(); // resource } } foreach (Question question in questions) { imsManifestWriter.WriteStartElement("resource"); imsManifestWriter.WriteAttributeString("identifier", "RES-" + question.Id.ToString()); imsManifestWriter.WriteAttributeString("type", "imsqti_item_xmlv2p1"); imsManifestWriter.WriteAttributeString("href", question.FileName); imsManifestWriter.WriteStartElement("metadata"); imsManifestWriter.WriteStartElement("imsmd:lom"); imsManifestWriter.WriteStartElement("imsmd:general"); imsManifestWriter.WriteElementString("imsmd:identifier", question.identifier); imsManifestWriter.WriteStartElement("imsmd:title"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString(question.Text); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:title imsManifestWriter.WriteElementString("imsmd:language", "ru"); imsManifestWriter.WriteStartElement("imsmd:description"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString(question.Description); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:description imsManifestWriter.WriteFullEndElement(); // imsmd:general imsManifestWriter.WriteStartElement("imsmd:lifecycle"); imsManifestWriter.WriteStartElement("imsmd:version"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "ru"); imsManifestWriter.WriteString("1.0"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:version imsManifestWriter.WriteStartElement("imsmd:status"); imsManifestWriter.WriteStartElement("imsmd:source"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "x-none"); imsManifestWriter.WriteString("LOMv1.0"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:source imsManifestWriter.WriteStartElement("imsmd:value"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "x-none"); imsManifestWriter.WriteString("Draft"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:value imsManifestWriter.WriteFullEndElement(); // imsmd:status imsManifestWriter.WriteFullEndElement(); // imsmd:lifecycle imsManifestWriter.WriteStartElement("imsmd:technical"); imsManifestWriter.WriteElementString("imsmd:format", "text/x-imsqti-item-xml"); imsManifestWriter.WriteFullEndElement(); // imsmd:technical imsManifestWriter.WriteStartElement("imsmd:rights"); imsManifestWriter.WriteStartElement("imsmd:description"); imsManifestWriter.WriteStartElement("imsmd:langstring"); imsManifestWriter.WriteAttributeString("xml:lang", "en"); imsManifestWriter.WriteString("(c) Visual Editor"); imsManifestWriter.WriteFullEndElement(); // imsmd:langstring imsManifestWriter.WriteFullEndElement(); // imsmd:description imsManifestWriter.WriteFullEndElement(); // imsmd:rights imsManifestWriter.WriteFullEndElement(); // imsmd:lom imsManifestWriter.WriteStartElement("imsmd:qtiMetadata"); imsManifestWriter.WriteElementString("imsmd:timeDependent", question.IsTimeDependent.ToString()); imsManifestWriter.WriteElementString("imsmd:interactionType", question.InteractionType.ToString()); if (question.IsAdaptive) { imsManifestWriter.WriteElementString("imsmd:feedbackType", "adaptive"); } else { imsManifestWriter.WriteElementString("imsmd:feedbackType", "none"); } imsManifestWriter.WriteElementString("imsmd:solutionAvailable", "true"); imsManifestWriter.WriteFullEndElement(); // imsmd:qtiMetadata imsManifestWriter.WriteFullEndElement(); // metadata imsManifestWriter.WriteStartElement("file"); imsManifestWriter.WriteAttributeString("href", question.FileName); imsManifestWriter.WriteFullEndElement(); // file foreach (string img in question.MmediaFiles) { imsManifestWriter.WriteStartElement("file"); imsManifestWriter.WriteAttributeString("href", "resources\\" + Path.GetFileName(img)); imsManifestWriter.WriteFullEndElement(); // file } imsManifestWriter.WriteFullEndElement(); // resource } //~~~файлы вопросов imsManifestWriter.WriteFullEndElement(); // resources imsManifestWriter.WriteFullEndElement(); // manifest imsManifestWriter.WriteEndDocument(); imsManifestWriter.Close(); }
internal static string GetLayerList(bool layersOnly) { MemoryStream ms = new MemoryStream(); using (XmlTextWriter xmlWriter = new XmlTextWriter(ms, System.Text.Encoding.UTF8)) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlWriter.WriteStartElement("LayerApi"); xmlWriter.WriteElementString("Status", "Success"); xmlWriter.WriteStartElement("LayerList"); xmlWriter.WriteAttributeString("Version", LayerManager.Version.ToString()); PrintLayers(xmlWriter, layersOnly, LayerMaps); xmlWriter.WriteEndElement(); xmlWriter.WriteFullEndElement(); xmlWriter.Close(); } byte[] data = ms.GetBuffer(); return Encoding.UTF8.GetString(data); }
public void Package() { StringWriter sw = new StringWriter(); using (XmlTextWriter xmlWriter = new XmlTextWriter(sw)) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlWriter.WriteStartElement("FileCabinet"); xmlWriter.WriteAttributeString("HeaderSize", "0x0BADFOOD"); xmlWriter.WriteStartElement("Files"); foreach (FileEntry entry in FileList) { xmlWriter.WriteStartElement("File"); xmlWriter.WriteAttributeString("Name", entry.Filename); xmlWriter.WriteAttributeString("Size", entry.Size.ToString()); xmlWriter.WriteAttributeString("Offset", entry.Offset.ToString()); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); xmlWriter.WriteFullEndElement(); xmlWriter.Close(); } string data = sw.ToString(); byte[] header = Encoding.UTF8.GetBytes(data); string sizeText = String.Format("0x{0:x8}", header.Length); data = data.Replace("0x0BADFOOD", sizeText); // Yeah this looks redundant, but we needed the data with the replaced size header = Encoding.UTF8.GetBytes(data); FileStream output = new FileStream(Filename, FileMode.Create); // Write Header output.Write(header, 0, header.Length); // Write each file foreach (FileEntry entry in FileList) { // using (FileStream fs = new FileStream(TempDirectory + "\\" + entry.Filename, FileMode.Open, FileAccess.Read)) using (FileStream fs = new FileStream(entry.Fullpath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[entry.Size]; if (fs.Read(buffer, 0, entry.Size) != entry.Size) { throw new SystemException( "One of the files in the collection is missing, corrupt or inaccessable"); } output.Write(buffer, 0, entry.Size); fs.Close(); } } output.Close(); }
private void WriteAnnotations(TrackingAnnotationCollection annotations, XmlTextWriter writer) { if ((annotations != null) && (annotations.Count != 0)) { writer.WriteStartElement("Annotations"); foreach (string str in annotations) { writer.WriteStartElement("Annotation"); if ((str == null) || (str.Length > 0)) { writer.WriteValue((str == null) ? string.Empty : str); writer.WriteEndElement(); } else { writer.WriteFullEndElement(); } } writer.WriteEndElement(); } }
public string GetProps() { MemoryStream ms = new MemoryStream(); using (XmlTextWriter xmlWriter = new XmlTextWriter(ms, System.Text.Encoding.UTF8)) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlWriter.WriteStartElement("LayerApi"); xmlWriter.WriteElementString("Status", "Success"); xmlWriter.WriteStartElement("Frame"); xmlWriter.WriteAttributeString("Class", this.GetType().ToString().Replace("TerraViewer.", "")); Type thisType = this.GetType(); PropertyInfo[] properties = thisType.GetProperties(); Type layerPropType = typeof(LayerProperty); foreach (PropertyInfo pi in properties) { bool safeToGet = false; object[] attributes = pi.GetCustomAttributes(false); foreach (object var in attributes) { if (var.GetType() == layerPropType) { safeToGet = true; break; } } if (safeToGet) { xmlWriter.WriteAttributeString(pi.Name, pi.GetValue(this, null).ToString()); } } xmlWriter.WriteEndElement(); xmlWriter.WriteFullEndElement(); xmlWriter.Close(); } byte[] data = ms.GetBuffer(); return Encoding.UTF8.GetString(data); }
private void saveElementPositions() { List<ColorPoint> points = new List<ColorPoint>(); Bitmap bmp = pictureBoxFrontMaskGraphics.Image as Bitmap; for (int x = 0; x < bmp.Width; x += Convert.ToInt32(numericUpDownAccuracy.Value)) for (int y = 0; y < bmp.Height; y += Convert.ToInt32(numericUpDownAccuracy.Value)) { Color pixel = bmp.GetPixel(x, y); if (pixel.A == 255) points.Add(new ColorPoint(pixel, new Point(x, y))); } XmlTextWriter textWriter = new XmlTextWriter(Path.Combine(folderBrowserDialogLevels.SelectedPath, "ground.xml"), null); textWriter.Formatting = Formatting.Indented; textWriter.WriteStartDocument(); textWriter.WriteStartElement("Elements"); Graphics gfx = Graphics.FromImage(bmp); Pen red = new Pen(Color.Blue); int maximum = points.Count; while (points.Count > 0) { Color currentColor = points[0].m_color; bool isFinishingElement = (currentColor.R == 0) && (currentColor.G == 0) && (currentColor.B == 0); // red.Color = Color.FromArgb(255, 255 - currentColor.R, 255 - currentColor.G, 255 - currentColor.B); List<Point> upPoints = new List<Point>(); List<Point> downPoints = new List<Point>(); List<Point> leftPoints = new List<Point>(); List<Point> rightPoints = new List<Point>(); // fixed hook points will stay there forever while "dynamic" hook points will be destroyed on player's contact Point lastPosition = points[0].m_point; List<Point> fixedHookPoints = new List<Point>(); List<Point> dynamicHookPoints = new List<Point>(); int leftest = int.MaxValue; int rightest = int.MinValue; int uppest = int.MaxValue; int downest = int.MinValue; for (int i = 0; i < points.Count; i++) { if (points[i].m_color == currentColor) { Point currentPoint = points[i].m_point; // search for hook-points Point firstHookPoint = new Point(currentPoint.X + 1, currentPoint.Y); for (int j = i + 1; j < points.Count; j++) if ((points[j].m_point == firstHookPoint) && (points[j].m_color != points[i].m_color)) { // sort of white --> fixed, otherwise dynamic! if (points[j].m_color.GetBrightness() >= 0.5f) fixedHookPoints.Add(points[j].m_point); else dynamicHookPoints.Add(points[j].m_point); points.Remove(points[j]); break; } lastPosition = currentPoint; if (currentPoint.X <= leftest) { if(currentPoint.X < leftest) leftPoints.Clear(); leftest = currentPoint.X; leftPoints.Add(currentPoint); } if (currentPoint.X >= rightest) { if (currentPoint.X > rightest) rightPoints.Clear(); rightest = currentPoint.X; rightPoints.Add(currentPoint); } if (currentPoint.Y <= uppest) { if (currentPoint.Y < uppest) upPoints.Clear(); uppest = currentPoint.Y; upPoints.Add(currentPoint); } if (currentPoint.Y >= downest) { if (currentPoint.Y > downest) downPoints.Clear(); downest = currentPoint.Y; downPoints.Add(currentPoint); } points.Remove(points[i]); i--; } backgroundWorkerWriteXML.ReportProgress(Convert.ToInt32((maximum - points.Count) / Convert.ToDouble(maximum) * 100)); } Point leftUp = leftPoints[0]; Point rightUp = upPoints[0]; Point leftDown = downPoints[0]; Point rightDown = rightPoints[0]; for (int i = 1; i < leftPoints.Count; i++) if (leftPoints[i].Y < leftUp.Y) leftUp.Y = leftPoints[i].Y; for (int i = 1; i < upPoints.Count; i++) if (upPoints[i].X > rightUp.X) rightUp.X = upPoints[i].X; for (int i = 1; i < rightPoints.Count; i++) if (rightPoints[i].Y > rightDown.Y) rightDown.Y = rightPoints[i].Y; for (int i = 1; i < downPoints.Count; i++) if (downPoints[i].X < leftDown.X) leftDown.X = downPoints[i].X; if(leftUp == leftDown) gfx.DrawPolygon(red, new Point[] { leftUp, leftDown, rightDown, rightUp }); // calculate the points into box2d-values for vertices // would have turned shorter with the xna vector 2 class, but i didn't want any urgent dependencies to the xna-framework Point position = new Point((leftUp.X + rightUp.X + leftDown.X + rightDown.X) / 4, (leftUp.Y + rightUp.Y + leftDown.Y + rightDown.Y) / 4); leftUp.X -= position.X; leftUp.Y -= position.Y; rightUp.X -= position.X; rightUp.Y -= position.Y; leftDown.X -= position.X; leftDown.Y -= position.Y; rightDown.X -= position.X; rightDown.Y -= position.Y; textWriter.WriteStartElement("Element"); textWriter.WriteStartElement("Position"); textWriter.WriteAttributeString("X", XmlConvert.ToString(position.X)); textWriter.WriteAttributeString("Y", XmlConvert.ToString(position.Y)); textWriter.WriteEndElement(); if (isFinishingElement) { textWriter.WriteStartElement("IsFinishingElement"); textWriter.WriteEndElement(); } foreach (Point p in fixedHookPoints) { textWriter.WriteStartElement("FixedHook"); textWriter.WriteAttributeString("X", XmlConvert.ToString(p.X)); textWriter.WriteAttributeString("Y", XmlConvert.ToString(p.Y)); textWriter.WriteEndElement(); } foreach (Point p in dynamicHookPoints) { textWriter.WriteStartElement("DynamicHook"); textWriter.WriteAttributeString("X", XmlConvert.ToString(p.X)); textWriter.WriteAttributeString("Y", XmlConvert.ToString(p.Y)); textWriter.WriteEndElement(); } // store the vertex points textWriter.WriteStartElement("Vertices"); textWriter.WriteStartElement("Point"); textWriter.WriteAttributeString("X", XmlConvert.ToString(rightUp.X)); textWriter.WriteAttributeString("Y", XmlConvert.ToString(rightUp.Y)); textWriter.WriteEndElement(); textWriter.WriteStartElement("Point"); textWriter.WriteAttributeString("X", XmlConvert.ToString(rightDown.X)); textWriter.WriteAttributeString("Y", XmlConvert.ToString(rightDown.Y)); textWriter.WriteEndElement(); textWriter.WriteStartElement("Point"); textWriter.WriteAttributeString("X", XmlConvert.ToString(leftDown.X)); textWriter.WriteAttributeString("Y", XmlConvert.ToString(leftDown.Y)); textWriter.WriteEndElement(); textWriter.WriteStartElement("Point"); textWriter.WriteAttributeString("X", XmlConvert.ToString(leftUp.X)); textWriter.WriteAttributeString("Y", XmlConvert.ToString(leftUp.Y)); textWriter.WriteEndElement(); textWriter.WriteEndElement(); textWriter.WriteEndElement(); } gfx.Dispose(); red.Dispose(); textWriter.WriteFullEndElement(); textWriter.Close(); }
/// <summary> /// Сериализует и сохраняет содержимое контроллера в файл в виде /// XML-схемы /// </summary> public void SaveToXmlFile(String path) { if (String.IsNullOrEmpty(path)) { path = Environment.CurrentDirectory + @"\config.xml"; } using (XmlTextWriter writer = new XmlTextWriter(path, null)) { writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("Network"); writer.WriteAttributeString("Name", NetworkName); // Сохраняем список устройств writer.WriteStartElement("Devices"); foreach (Device device in _Devices) { writer.WriteStartElement("Device"); // Сохраняем свойства элемента "Device" writer.WriteAttributeString("Address", device.Address.ToString()); writer.WriteAttributeString("Description", device.Description); writer.WriteAttributeString("Status", device.Status.ToString()); // Сохраняем узлы элемента "Device" // Сохраняем регистры хранения writer.WriteStartElement("HoldingRegisters"); foreach (HoldingRegister register in device.HoldingRegisters) { writer.WriteStartElement("HoldingRegister"); writer.WriteAttributeString("Address", register.Address.ToString()); writer.WriteStartElement("Value"); writer.WriteValue(register.Value); writer.WriteFullEndElement(); // "Value" writer.WriteStartElement("Description"); writer.WriteString(register.Description); writer.WriteFullEndElement(); // "Description" writer.WriteFullEndElement(); // "HoldingRegister" } writer.WriteFullEndElement(); // "HoldingRegisters" // Сохраняем входные регистры writer.WriteStartElement("InputRegisters"); foreach (InputRegister register in device.InputRegisters) { writer.WriteStartElement("InputRegister"); writer.WriteAttributeString("Address", register.Address.ToString()); writer.WriteStartElement("Value"); writer.WriteValue(register.Value); writer.WriteFullEndElement(); // "Value" writer.WriteStartElement("Description"); writer.WriteString(register.Description); writer.WriteFullEndElement(); // "Description" writer.WriteFullEndElement(); // "InputRegister" } writer.WriteFullEndElement(); // "InputRegisters" // Сохраняем дискретные входы/выходы writer.WriteStartElement("Сoils"); foreach (Coil coil in device.Coils) { writer.WriteStartElement("Coil"); writer.WriteAttributeString("Address", coil.Address.ToString()); writer.WriteStartElement("Value"); writer.WriteValue(coil.Value); writer.WriteFullEndElement(); // "Value" writer.WriteStartElement("Description"); writer.WriteString(coil.Description); writer.WriteFullEndElement(); // "Description" writer.WriteFullEndElement(); // "Coil" } writer.WriteFullEndElement(); // "Сoils" // Сохраняем дискретные входы writer.WriteStartElement("DiscretesInputs"); foreach (DiscreteInput dicsreteInput in device.DiscretesInputs) { writer.WriteStartElement("DiscreteInput"); writer.WriteAttributeString("Address", dicsreteInput.Address.ToString()); writer.WriteStartElement("Value"); writer.WriteValue(dicsreteInput.Value); writer.WriteFullEndElement(); // "Value" writer.WriteStartElement("Description"); writer.WriteString(dicsreteInput.Description); writer.WriteFullEndElement(); // "Description" writer.WriteFullEndElement(); // "DiscreteInput" } writer.WriteFullEndElement(); // "DiscretesInputs" // Сохраняем файлы устройства writer.WriteStartElement("Files"); foreach (File file in device.Files) { writer.WriteStartElement("File"); writer.WriteAttributeString("Number", file.Number.ToString()); writer.WriteAttributeString("Description", file.Description); writer.WriteStartElement("Records"); foreach (Record record in file.Records) { writer.WriteStartElement("Record"); writer.WriteAttributeString("Number", record.Address.ToString()); writer.WriteAttributeString("Description", record.Description); writer.WriteStartElement("Value"); writer.WriteValue(record.Value); writer.WriteFullEndElement(); // "Value" writer.WriteFullEndElement(); // "Record" } writer.WriteFullEndElement(); // "Records" writer.WriteFullEndElement(); // "File" } writer.WriteFullEndElement(); // "Files" writer.WriteFullEndElement(); // "Device" } writer.WriteFullEndElement(); // "Devices" writer.WriteFullEndElement(); // "Network" } return; }
public void SaveToXml(bool forExport) { string outFile; if (!Directory.Exists(Properties.Settings.Default.CahceDirectory + @"LayerTemp\")) { Directory.CreateDirectory(Properties.Settings.Default.CahceDirectory + @"LayerTemp\"); } if (!forExport) { //Use a guid if the Title is only non-legal characters or is empty if (String.IsNullOrEmpty(filename)) { filename = Properties.Settings.Default.CahceDirectory + @"LayerTemp\" + id + ".wwtxml"; } outFile = filename; } else { outFile = TempFilename; } using (var xmlWriter = new XmlTextWriter(outFile, Encoding.UTF8)) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlWriter.WriteStartElement("LayerContainer"); xmlWriter.WriteAttributeString("ID", id); List<Guid> masterList = null; if (!string.IsNullOrEmpty(TopLevel)) { masterList = CreateLayerMasterListFromFrame(TopLevel); } else { masterList = CreateLayerMasterList(); } // This will now save and sync emtpy frames... var referencedFrames = GetReferenceFrameList(); xmlWriter.WriteStartElement("ReferenceFrames"); foreach (var item in referencedFrames) { item.SaveToXml(xmlWriter); } xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("Layers"); foreach (var t in masterList) { if (LayerManager.LayerList.ContainsKey(t)) { LayerManager.LayerList[t].SaveToXml(xmlWriter); } } xmlWriter.WriteEndElement(); xmlWriter.WriteFullEndElement(); xmlWriter.Close(); } }
private void saveMisc() { Bitmap bmp = pictureBoxDot.Image as Bitmap; // dot is a circle with centerpoint in the middle of the gfx so we need only the radius as size int radius = bmp.Width; for (int x = 0; x < bmp.Width; x++) if (bmp.GetPixel(x, bmp.Height / 2).A == 0) radius--; radius /= 2; XmlTextWriter textWriter = new XmlTextWriter(Path.Combine(folderBrowserDialogLevels.SelectedPath, "misc.xml"), null); textWriter.Formatting = Formatting.Indented; textWriter.WriteStartDocument(); textWriter.WriteStartElement("Parameters"); textWriter.WriteStartElement("Dot"); textWriter.WriteAttributeString("X", XmlConvert.ToString(pictureBoxDot.Location.X + pictureBoxDot.Size.Width / 2 + panelGraphics.HorizontalScroll.Value)); textWriter.WriteAttributeString("Y", XmlConvert.ToString(pictureBoxDot.Location.Y + pictureBoxDot.Size.Height / 2 + panelGraphics.VerticalScroll.Value)); textWriter.WriteAttributeString("Radius", XmlConvert.ToString(radius)); textWriter.WriteEndElement(); textWriter.WriteStartElement("Goal"); textWriter.WriteAttributeString("LettersPercentage", textBoxLettersNeeded.Text); textWriter.WriteAttributeString("TimeSeconds", textBoxTime.Text); textWriter.WriteEndElement(); textWriter.WriteFullEndElement(); textWriter.Close(); }
///************************************************************************* /// Method: saveFunctionXmlDocument /// Description: recreating functions.xml document /// /// Parameters: /// functionXMLNavigator : /// /// fileNameToSaveAs : filename /// /// Return Value: None ///************************************************************************* public void saveFunctionXmlDocument(FunctionXMLNavigator functionXMLNavigator, string fileNameToSaveAs,string fileEncoding,bool isValidationRequired) { XmlTextWriter saveFunctionXml; switch(fileEncoding.ToUpper()) { case "UTF-8": case "": { saveFunctionXml = new XmlTextWriter(fileNameToSaveAs,System.Text.UTF8Encoding.UTF8); saveFunctionXml.Formatting = Formatting.Indented; saveFunctionXml.WriteRaw( "<?xml version= \"1.0\"?>" ); break; } case "UTF-7": { saveFunctionXml = new XmlTextWriter(fileNameToSaveAs,System.Text.UTF7Encoding.UTF7); saveFunctionXml.Formatting = Formatting.Indented; saveFunctionXml.WriteRaw( "<?xml version= \"1.0\" encoding=\"UTF-7\"?>" ); break; } case "ASCII": { saveFunctionXml = new XmlTextWriter(fileNameToSaveAs,System.Text.ASCIIEncoding.ASCII); saveFunctionXml.Formatting = Formatting.Indented; saveFunctionXml.WriteRaw( "<?xml version= \"1.0\" encoding=\"ASCII\"?>" ); break; } case "Unicode": { saveFunctionXml = new XmlTextWriter(fileNameToSaveAs,System.Text.UnicodeEncoding.Unicode); saveFunctionXml.Formatting = Formatting.Indented; saveFunctionXml.WriteRaw( "<?xml version= \"1.0\" encoding=\"Unicode\"?>" ); break; } default: { saveFunctionXml = new XmlTextWriter(fileNameToSaveAs,null); saveFunctionXml.Formatting = Formatting.Indented; saveFunctionXml.WriteRaw( "<?xml version= \"1.0\"?>" ); break; } } if(isValidationRequired) { saveFunctionXml.WriteDocType("Functions",null,"functions.dtd",""); } saveFunctionXml.WriteStartElement("Functions"); foreach(string FunctionNameAsKey in FunctionTableByName.Keys) { Function FunctionToSave = functionXMLNavigator.GetFunctionByName(FunctionNameAsKey); ///Element = Function saveFunctionXml.WriteStartElement("Function"); //Element = FunctionName saveFunctionXml.WriteStartElement("FunctionName"); saveFunctionXml.WriteString(FunctionToSave.FunctionName.ToString()); saveFunctionXml.WriteFullEndElement(); //Element = OriginalDll saveFunctionXml.WriteStartElement("OriginalDll"); saveFunctionXml.WriteString(FunctionToSave.OriginalDll.ToString()); saveFunctionXml.WriteFullEndElement(); //Element = InterceptedDll saveFunctionXml.WriteStartElement("InterceptedDll"); saveFunctionXml.WriteString(FunctionToSave.InterceptedDll.ToString()); saveFunctionXml.WriteFullEndElement(); //Element = ReplacementFunctionName saveFunctionXml.WriteStartElement("ReplacementFunctionName"); saveFunctionXml.WriteString(FunctionToSave.ReplacementFunctionName.ToString()); saveFunctionXml.WriteFullEndElement(); //Element = ReturnType saveFunctionXml.WriteStartElement("ReturnType"); saveFunctionXml.WriteString(FunctionToSave.ReturnType.ToString()); saveFunctionXml.WriteFullEndElement(); //Element = Modifier for(int indexModifier =0; indexModifier < FunctionToSave.Modifiers.Count;indexModifier ++) { saveFunctionXml.WriteStartElement("TypeModifier"); saveFunctionXml.WriteString(FunctionToSave.Modifiers[indexModifier].ToString()); saveFunctionXml.WriteFullEndElement(); } //Element = CallingConventionModifier for(int indexCallingConventionModifier =0; indexCallingConventionModifier < FunctionToSave.CallingConventionModifier.Count;indexCallingConventionModifier ++) { saveFunctionXml.WriteStartElement("CallingConventionModifier"); saveFunctionXml.WriteString(FunctionToSave.CallingConventionModifier[indexCallingConventionModifier].ToString()); saveFunctionXml.WriteFullEndElement(); } //Element = Category saveFunctionXml.WriteStartElement("Category"); saveFunctionXml.WriteString(FunctionToSave.Category.ToString()); saveFunctionXml.WriteFullEndElement(); ///Element = ReturnValue foreach(ReturnValue returnValue in FunctionToSave.ReturnValue) { ///Element = ReturnValue saveFunctionXml.WriteStartElement("ReturnValue"); ///Attribute = Type if(returnValue.Type != null) { saveFunctionXml.WriteAttributeString("Type",returnValue.Type.ToString()); } ///Attribute = ValueOperator if(returnValue.ValueOperator != null) { saveFunctionXml.WriteAttributeString("ValueOperator",returnValue.ValueOperator.ToString()); } saveFunctionXml.WriteString(returnValue.NodeValue.ToString()); saveFunctionXml.WriteFullEndElement(); } ///Element = Exception for(int indexException =0; indexException < FunctionToSave.Exception.Count;indexException ++) { saveFunctionXml.WriteStartElement("Exception"); saveFunctionXml.WriteString(FunctionToSave.Exception[indexException].ToString()); saveFunctionXml.WriteFullEndElement(); } /// Element = HelpLink saveFunctionXml.WriteStartElement("HelpLink"); saveFunctionXml.WriteString(FunctionToSave.HelpLink.ToString()); saveFunctionXml.WriteFullEndElement(); /// Element = Param foreach(Parameter param in FunctionToSave.Parameter) { ///Element = Param saveFunctionXml.WriteStartElement("Param"); ///Attribute = Index if(param.Index != -1) { saveFunctionXml.WriteAttributeString("Index",param.Index.ToString()); } ///Attribute = Type if(param.Type != null) { saveFunctionXml.WriteAttributeString("Type",param.Type.ToString()); } ///Attribute = CompareAs if(param.CompareAs != null) { saveFunctionXml.WriteAttributeString("CompareAs",param.CompareAs.ToString()); } ///Attribute = Access if(param.Access != null) { saveFunctionXml.WriteAttributeString("Access",param.Access.ToString()); } ///Attribute = PointsToResource if(param.PointsToResource != null) { saveFunctionXml.WriteAttributeString("PointsToResource",param.PointsToResource.ToString()); } ///Attribute = ConcatWith if(param.ConcatWith != null) { saveFunctionXml.WriteAttributeString("ConcatWith",param.ConcatWith.ToString()); } ///Attribute = MapTo if(param.MapTo != null) { saveFunctionXml.WriteAttributeString("MapTo",param.MapTo.ToString()); } saveFunctionXml.WriteString(param.Name.ToString()); saveFunctionXml.WriteFullEndElement(); } ///Element = ErrorCode foreach(ErrorCode errorCode in FunctionToSave.ErrorCode) { ///Element = ErrorCode saveFunctionXml.WriteStartElement("ErrorCode"); ///Attribute = IdentifyBy if(errorCode.IdentifiedBy != null) { saveFunctionXml.WriteAttributeString("IdentifyBy",errorCode.IdentifiedBy.ToString()); } ///Attribute = Type if(errorCode.Type != null) { saveFunctionXml.WriteAttributeString("Type",errorCode.Type.ToString()); } saveFunctionXml.WriteString(errorCode.NodeValue.ToString()); saveFunctionXml.WriteFullEndElement(); } saveFunctionXml.WriteFullEndElement(); } saveFunctionXml.WriteFullEndElement(); //closing xmlwriter. saveFunctionXml.Close(); }
//************************************************************************* // Method: SaveProject // // Description: Saves project settings to an XML file. // // Parameters: // fileName - file to save project to. // useExistingFilename - if true, fileName param. is ignored and the existing // filename is used // // Return Value: none //************************************************************************* public void SaveProject(String fileName, bool useExistingFilename) { if (!useExistingFilename) SavedProjectFileName = fileName; InterceptedFunctionDB db = InterceptedFunctionDB.GetInstance("functions.xml"); RegistryHelper helper = RegistryHelper.getInstance(); string dtdName = helper.GetDTDFolder(); if (dtdName == null) dtdName = "projectfile.dtd"; else if (dtdName.EndsWith("\\")) dtdName = string.Concat(dtdName, "projectfile.dtd"); else dtdName = string.Concat(dtdName, "\\projectfile.dtd"); XmlTextWriter xwriter = new XmlTextWriter(SavedProjectFileName,System.Text.Encoding.UTF8); xwriter.Formatting = Formatting.Indented; xwriter.Indentation = 4; xwriter.WriteStartDocument(false); xwriter.WriteDocType ("Project", null, dtdName, null); xwriter.WriteStartElement ("Project"); foreach(ProcessMdiWindow window in mdiWindowList) { xwriter.WriteStartElement ("ApplicationUnderTest"); xwriter.WriteStartElement ("AppInfo"); xwriter.WriteAttributeString ("ApplicationPathAndName", window.ProcessFile); if (window.UseProcessFile) xwriter.WriteAttributeString ("InjectMode", "LAUNCH"); else xwriter.WriteAttributeString ("InjectMode", "ATTACH"); xwriter.WriteAttributeString ("StartPaused", window.AppPaused.ToString()); xwriter.WriteFullEndElement (); //End for AppInfo xwriter.WriteStartElement ("FilteredFunctions"); foreach (string fName in window.FilteredOutFunctions) { InterceptedFunction function = db.GetFunctionByName(fName); if (function != null) { xwriter.WriteStartElement ("FilteredFunction"); xwriter.WriteAttributeString ("FunctionName", function.Name); xwriter.WriteFullEndElement(); } } xwriter.WriteFullEndElement(); //end for FilteredFunctions xwriter.WriteStartElement ("Faults"); xwriter.WriteStartElement ("DiskFaults"); EnumerateCheckAndSaveFaults ("Disk", ref xwriter, window); xwriter.WriteFullEndElement(); xwriter.WriteStartElement ("MemoryFaults"); EnumerateCheckAndSaveFaults ("Memory", ref xwriter, window); xwriter.WriteFullEndElement(); xwriter.WriteStartElement ("NetworkFaults"); EnumerateCheckAndSaveFaults ("Network", ref xwriter, window); xwriter.WriteFullEndElement(); xwriter.WriteFullEndElement(); //End for "Faults" xwriter.WriteStartElement ("Limits"); xwriter.WriteStartElement ("DiskSpaceLimit"); xwriter.WriteAttributeString ("LimitActivated", window.LimitDiskUsage.ToString()); xwriter.WriteAttributeString ("Limit", window.MaxDiskUsage.ToString()); xwriter.WriteAttributeString ("LimitUnit", window.MaxDiskUsageUnit); xwriter.WriteFullEndElement(); xwriter.WriteStartElement ("MemorySpaceLimit"); xwriter.WriteAttributeString ("LimitActivated", window.LimitMemoryUsage.ToString()); xwriter.WriteAttributeString ("Limit", window.MaxMemoryUsage.ToString()); xwriter.WriteAttributeString ("LimitUnit", window.MaxMemoryUsageUnit); xwriter.WriteFullEndElement(); xwriter.WriteStartElement ("NetworkThrottle"); xwriter.WriteAttributeString ("ThrottleActivated", window.LimitNetworkSpeed.ToString()); xwriter.WriteAttributeString ("ThrottlePercent", window.MaxNetworkSpeed.ToString()); xwriter.WriteFullEndElement(); xwriter.WriteFullEndElement(); //End for "Limits" xwriter.WriteStartElement ("ScheduledTests"); foreach (ListViewItem item in window.GetScheduledTests()) { InterceptedFunction f = InterceptedFunctionDB.GetInstance("functions.xml").GetFunctionByName(item.SubItems[1].Text); if (f != null) { xwriter.WriteStartElement ("ScheduledTest"); xwriter.WriteAttributeString("TestID",item.SubItems[0].Text); xwriter.WriteAttributeString("FunctionName", f.Name); xwriter.WriteAttributeString("Category", f.Category); xwriter.WriteAttributeString("ErrorCode", item.SubItems[2].Text); xwriter.WriteAttributeString("ReturnValue", item.SubItems[3].Text); xwriter.WriteAttributeString("Parameters", item.SubItems[4].Text); xwriter.WriteFullEndElement(); } } xwriter.WriteFullEndElement(); //End for "ScheduledTests" xwriter.WriteFullEndElement(); //end for ApplicationUnderTest } xwriter.WriteFullEndElement(); //End for "Project" xwriter.WriteEndDocument (); xwriter.Flush(); xwriter.Close(); }
// This is taken almost directly from GAIM. There must be a // better way to do this... public static void Serialize (Gtk.TextBuffer buffer, Gtk.TextIter start, Gtk.TextIter end, XmlTextWriter xml) { Stack<Gtk.TextTag> tag_stack = new Stack<Gtk.TextTag> (); Stack<Gtk.TextTag> replay_stack = new Stack<Gtk.TextTag> (); Stack<Gtk.TextTag> continue_stack = new Stack<Gtk.TextTag> (); Gtk.TextIter iter = start; Gtk.TextIter next_iter = start; next_iter.ForwardChar (); bool line_has_depth = false; int prev_depth_line = -1; int prev_depth = -1; xml.WriteStartElement (null, "note-content", null); xml.WriteAttributeString ("version", "0.1"); // Insert any active tags at start into tag_stack... foreach (Gtk.TextTag start_tag in start.Tags) { if (!start.TogglesTag (start_tag)) { tag_stack.Push (start_tag); WriteTag (start_tag, xml, true); } } while (!iter.Equal (end) && iter.Char != null) { DepthNoteTag depth_tag = ((NoteBuffer)buffer).FindDepthTag (iter); // If we are at a character with a depth tag we are at the // start of a bulleted line if (depth_tag != null && iter.StartsLine()) { line_has_depth = true; if (iter.Line == prev_depth_line + 1) { // Line part of existing list if (depth_tag.Depth == prev_depth) { // Line same depth as previous // Close previous <list-item> xml.WriteEndElement (); } else if (depth_tag.Depth > prev_depth) { // Line of greater depth xml.WriteStartElement (null, "list", null); for (int i = prev_depth + 2; i <= depth_tag.Depth; i++) { // Start a new nested list xml.WriteStartElement (null, "list-item", null); xml.WriteStartElement (null, "list", null); } } else { // Line of lesser depth // Close previous <list-item> // and nested <list>s xml.WriteEndElement (); for (int i = prev_depth; i > depth_tag.Depth; i--) { // Close nested <list> xml.WriteEndElement (); // Close <list-item> xml.WriteEndElement (); } } } else { // Start of new list xml.WriteStartElement (null, "list", null); for (int i = 1; i <= depth_tag.Depth; i++) { xml.WriteStartElement (null, "list-item", null); xml.WriteStartElement (null, "list", null); } } prev_depth = depth_tag.Depth; // Start a new <list-item> WriteTag (depth_tag, xml, true); } // Output any tags that begin at the current position foreach (Gtk.TextTag tag in iter.Tags) { if (iter.BeginsTag (tag)) { if (!(tag is DepthNoteTag) && NoteTagTable.TagIsSerializable(tag)) { WriteTag (tag, xml, true); tag_stack.Push (tag); } } } // Reopen tags that continued across indented lines // or into or out of lines with a depth while (continue_stack.Count > 0 && ((depth_tag == null && iter.StartsLine ()) || iter.LineOffset == 1)) { Gtk.TextTag continue_tag = continue_stack.Pop(); if (!TagEndsHere (continue_tag, iter, next_iter) && iter.HasTag (continue_tag)) { WriteTag (continue_tag, xml, true); tag_stack.Push (continue_tag); } } // Hidden character representing an anchor if (iter.Char[0] == (char) 0xFFFC) { Logger.Info ("Got child anchor!"); if (iter.ChildAnchor != null) { string serialize = (string) iter.ChildAnchor.Data ["serialize"]; if (serialize != null) xml.WriteRaw (serialize); } // Line Separator character } else if (iter.Char == "\u2028") { xml.WriteCharEntity ('\u2028'); } else if (depth_tag == null) { xml.WriteString (iter.Char); } bool end_of_depth_line = line_has_depth && next_iter.EndsLine (); bool next_line_has_depth = false; if (iter.Line < buffer.LineCount - 1) { Gtk.TextIter next_line = buffer.GetIterAtLine(iter.Line+1); next_line_has_depth = ((NoteBuffer)buffer).FindDepthTag (next_line) != null; } bool at_empty_line = iter.EndsLine () && iter.StartsLine (); if (end_of_depth_line || (next_line_has_depth && (next_iter.EndsLine () || at_empty_line))) { // Close all tags in the tag_stack while (tag_stack.Count > 0) { Gtk.TextTag existing_tag = tag_stack.Pop (); // Any tags which continue across the indented // line are added to the continue_stack to be // reopened at the start of the next <list-item> if (!TagEndsHere (existing_tag, iter, next_iter)) { continue_stack.Push (existing_tag); } WriteTag (existing_tag, xml, false); } } else { foreach (Gtk.TextTag tag in iter.Tags) { if (TagEndsHere (tag, iter, next_iter) && NoteTagTable.TagIsSerializable(tag) && !(tag is DepthNoteTag)) { while (tag_stack.Count > 0) { Gtk.TextTag existing_tag = tag_stack.Pop (); if (!TagEndsHere (existing_tag, iter, next_iter)) { replay_stack.Push (existing_tag); } WriteTag (existing_tag, xml, false); } // Replay the replay queue. // Restart any tags that // overlapped with the ended // tag... while (replay_stack.Count > 0) { Gtk.TextTag replay_tag = replay_stack.Pop (); tag_stack.Push (replay_tag); WriteTag (replay_tag, xml, true); } } } } // At the end of the line record that it // was the last line encountered with a depth if (end_of_depth_line) { line_has_depth = false; prev_depth_line = iter.Line; } // If we are at the end of a line with a depth and the // next line does not have a depth line close all <list> // and <list-item> tags that remain open if (end_of_depth_line && !next_line_has_depth) { for (int i = prev_depth; i > -1; i--) { // Close <list> xml.WriteFullEndElement (); // Close <list-item> xml.WriteFullEndElement (); } prev_depth = -1; } iter.ForwardChar (); next_iter.ForwardChar (); } // Empty any trailing tags left in tag_stack.. while (tag_stack.Count > 0) { Gtk.TextTag tail_tag = tag_stack.Pop (); WriteTag (tail_tag, xml, false); } xml.WriteEndElement (); // </note-content> }
public override void Execute(object @object) { if (!Enabled) { return; } // Сохраняет xml в ProjectTrueLocation. var path = Path.Combine(Warehouse.Warehouse.ProjectTrueLocation, string.Concat("ProjectName", ".xml")); var xmlWriter = new XmlTextWriter(path, Encoding.UTF8) { Formatting = Formatting.Indented }; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("project"); xmlWriter.WriteAttributeString("name", Warehouse.Warehouse.Instance.CourseTree.Nodes[0].Text); xmlWriter.WriteAttributeString("type", "new"); WalkTree(Warehouse.Warehouse.Instance.CourseTree.Nodes); RibbonStatusStripEx.Instance.ModulesCount = modulesCount; WriteModules(Warehouse.Warehouse.Instance.CourseTree.Nodes[0] as CourseItem, xmlWriter); #region Запись компетенций // Запись внешних компетенций. foreach (var c in Warehouse.Warehouse.Instance.ExternalConcepts) { xmlWriter.WriteStartElement("concept"); xmlWriter.WriteAttributeString("name", c.Text); xmlWriter.WriteAttributeString("id", "#elem{" + c.Id.ToString().ToUpper() + "}"); xmlWriter.WriteAttributeString("io", "i"); xmlWriter.WriteEndElement(); } // Запись внутренних компетенций. foreach (var c in Warehouse.Warehouse.Instance.InternalConcepts) { xmlWriter.WriteStartElement("concept"); xmlWriter.WriteAttributeString("name", c.Text); xmlWriter.WriteAttributeString("id", "#elem{" + c.Id.ToString().ToUpper() + "}"); xmlWriter.WriteAttributeString("io", "o"); xmlWriter.WriteEndElement(); } // Запись внешних профилей. foreach (var c in Warehouse.Warehouse.Instance.ExternalConcepts) { if (c.IsProfile) { xmlWriter.WriteStartElement("profile"); xmlWriter.WriteAttributeString("concept_id", "#elem{" + c.Id.ToString().ToUpper() + "}"); xmlWriter.WriteAttributeString("min", c.LowerBound.ToString()); xmlWriter.WriteEndElement(); } } // Запись внутренних профилей. foreach (var c in Warehouse.Warehouse.Instance.InternalConcepts) { if (c.IsProfile) { xmlWriter.WriteStartElement("profile"); xmlWriter.WriteAttributeString("concept_id", "#elem{" + c.Id.ToString().ToUpper() + "}"); xmlWriter.WriteAttributeString("min", c.LowerBound.ToString()); xmlWriter.WriteEndElement(); } } #endregion xmlWriter.WriteFullEndElement(); xmlWriter.Close(); }
public override void WriteXml(XmlTextWriter xmlWriter) { xmlWriter.WriteStartElement("question"); xmlWriter.WriteAttributeString("name", question.Text); xmlWriter.WriteAttributeString("id", "#module{" + question.Id.ToString().ToUpper() + "}"); if (question.NextQuestion != null) { xmlWriter.WriteAttributeString("next_question", "#module{" + question.NextQuestion.Id.ToString().ToUpper() + "}"); } xmlWriter.WriteAttributeString("type", "checkbox"); xmlWriter.WriteAttributeString("time", question.TimeRestriction.ToString()); #region Контент вопроса xmlWriter.WriteStartElement("html_text"); xmlWriter.WriteAttributeString("id", "{" + Guid.NewGuid().ToString().ToUpper() + "}"); xmlWriter.WriteCData(HtmlToXml(question.DocumentHtml)); xmlWriter.WriteFullEndElement(); #endregion #region Ответы xmlWriter.WriteStartElement("answer_block"); xmlWriter.WriteAttributeString("cols", "1"); var i = 0; foreach (var r in question.Responses) { xmlWriter.WriteStartElement("answer"); i++; r.NativeId = string.Concat("a", i); xmlWriter.WriteAttributeString("id", r.NativeId); xmlWriter.WriteStartElement("html_text"); xmlWriter.WriteAttributeString("id", "{" + Guid.NewGuid().ToString().ToUpper() + "}"); xmlWriter.WriteCData(HtmlToXml(r.DocumentHtml)); xmlWriter.WriteFullEndElement(); xmlWriter.WriteFullEndElement(); } xmlWriter.WriteFullEndElement(); #endregion #region Варианты ответа if (question.ResponseVariants != null) { foreach (ResponseVariant rv in question.ResponseVariants) { xmlWriter.WriteStartElement("answer_variants"); xmlWriter.WriteAttributeString("type", "nonstrict"); xmlWriter.WriteAttributeString("weight", rv.Weight.ToString().Replace(",", ".")); #region Следующий вопрос в зависимости от варианта ответа!!!!!!!!!!!!!!!!!!!! // var tm = Warehouse.Warehouse.Instance.CourseTree.CurrentNode.Parent as TestModule; var tm = this.question.Parent as TestModule; if (tm != null) { foreach (var question1 in tm.Questions) if (question1.Text == rv.NextQuestion || "#module{" + question1.Id.ToString().ToUpper() + "}" == rv.NextQuestion) { xmlWriter.WriteAttributeString("next_question", "#module{" + question1.Id.ToString().ToUpper() + "}"); //xmlWriter.WriteAttributeString("next_question", question1.Text); } } #endregion if (rv.Responses != null) { foreach (Response r in rv.Responses) { xmlWriter.WriteStartElement("checked"); xmlWriter.WriteAttributeString("answer_id", r.NativeId); xmlWriter.WriteFullEndElement(); } } if (!string.IsNullOrEmpty(rv.Hint)) { xmlWriter.WriteStartElement("hint"); xmlWriter.WriteAttributeString("id", Guid.NewGuid().ToString()); xmlWriter.WriteCData(HtmlToXml(rv.Hint)); xmlWriter.WriteFullEndElement(); } xmlWriter.WriteFullEndElement(); } } else { xmlWriter.WriteStartElement("answer_variants"); xmlWriter.WriteAttributeString("type", "nonstrict"); xmlWriter.WriteAttributeString("weight", "0"); xmlWriter.WriteFullEndElement(); } #endregion #region Подсказка xmlWriter.WriteStartElement("hint"); xmlWriter.WriteAttributeString("id", Guid.NewGuid().ToString()); xmlWriter.WriteCData(HtmlToXml(question.Hint)); xmlWriter.WriteFullEndElement(); #endregion if (!(question.Parent is Group)) { xmlWriter.WriteStartElement("mark"); xmlWriter.WriteAttributeString("value", question.Marks.ToString()); if (question.Profile != null) { xmlWriter.WriteAttributeString("concept_id", "#elem{" + question.Profile.Id.ToString().ToUpper() + "}"); } xmlWriter.WriteFullEndElement(); } xmlWriter.WriteFullEndElement(); }
/// <summary> /// Рекурсивная процедура для преобразования html в xml. /// </summary> /// <param name="htmlText">HTML текст, который нужно преобразовать.</param> /// <param name="writer">XmlTextWriter для записи xml сразу в выходной поток.</param> public void ConvertHtmlStringToXml(string htmlText, XmlTextWriter writer) { Match tag; HtmlTextWork htw = new HtmlTextWork(); #region мое творение MatchCollection imgTags = Regex.Matches(htmlText, "<img[^>]*>", RegexOptions.IgnoreCase); foreach (Match imtag in imgTags) { // определяем границы тега htw.GetTagBounds(htmlText, imtag.ToString()); htw.ShiftLastIndex(ref htmlText); // считываем значение аттрибута src string src = htw.GetValue("src"); //if (Path.GetExtension(src) == ".mp4" || Path.GetExtension(src) == ".flv" || Path.GetExtension(src) == ".mp3" || Path.GetExtension(src) == ".swf") if (Path.GetFileNameWithoutExtension(src) == "Aud" || Path.GetFileNameWithoutExtension(src) == "Vid" || Path.GetFileNameWithoutExtension(src) == "Anim") { string src_ = htw.GetValue("src_"); // удаляем тег из текста htw.RemoveTag(ref htmlText); // вставляем вместо удалённого тега нужный текст //string sf = Path.Combine(Warehouse.Warehouse.RelativeImagesDirectory, Path.GetFileName(src)); htmlText = htmlText.Insert(htw.OpenTagStartIndex, "<object" + " data=\"" + src_ +"\"" + ">" + " </object>"); } } #endregion var greekSymbols = Regex.Matches(htmlText, "[Α-Ωα-ω¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿™•∑∏∫∂√∞ƒ≤≥≠≡…′″∃∈∋∧∨∩∪∼≈⊂⊃⊆⊇⊕⊥°→×÷∀]", RegexOptions.IgnoreCase); int index; if (greekSymbols.Count != 0) { for (var i = greekSymbols.Count; i > 0; i--) { var symbol = greekSymbols[i - 1].Value; index = greekSymbols[i - 1].Index; htmlText = htmlText.Remove(index, 1); htmlText = htmlText.Insert(index, string.Concat("&#", char.ConvertToUtf32(symbol, 0), ";")); } } greekSymbols = Regex.Matches(htmlText, "[Ë]", RegexOptions.IgnoreCase); if (greekSymbols.Count != 0) { for (var i = greekSymbols.Count; i > 0; i--) { index = greekSymbols[i - 1].Index; htmlText = htmlText.Remove(index, 1); htmlText = htmlText.Insert(index, "Ë"); } } greekSymbols = Regex.Matches(htmlText, "[Ï]", RegexOptions.IgnoreCase); if (greekSymbols.Count != 0) { for (var i = greekSymbols.Count; i > 0; i--) { index = greekSymbols[i - 1].Index; htmlText = htmlText.Remove(index, 1); htmlText = htmlText.Insert(index, "Ï"); } } greekSymbols = Regex.Matches(htmlText, "[Æ]", RegexOptions.IgnoreCase); if (greekSymbols.Count != 0) { for (var i = greekSymbols.Count; i > 0; i--) { index = greekSymbols[i - 1].Index; htmlText = htmlText.Remove(index, 1); htmlText = htmlText.Insert(index, "Æ"); } } greekSymbols = Regex.Matches(htmlText, "[Ä]", RegexOptions.IgnoreCase); if (greekSymbols.Count != 0) { for (var i = greekSymbols.Count; i > 0; i--) { index = greekSymbols[i - 1].Index; htmlText = htmlText.Remove(index, 1); htmlText = htmlText.Insert(index, "Ä"); } } greekSymbols = Regex.Matches(htmlText, "[Þ]", RegexOptions.IgnoreCase); if (greekSymbols.Count != 0) { for (var i = greekSymbols.Count; i > 0; i--) { index = greekSymbols[i - 1].Index; htmlText = htmlText.Remove(index, 1); htmlText = htmlText.Insert(index, "Þ"); } } do { // поиск тегов tag = Regex.Match(htmlText, @"<[^>]+>"); if (tag.ToString() != "") { if (htmlText.IndexOf(tag.ToString()) != 0) { writer.WriteString(htmlText.Substring(0, htmlText.IndexOf(tag.ToString()))); htmlText = htmlText.Remove(0, htmlText.IndexOf(tag.ToString())); } htw.GetTagBounds(htmlText, tag.ToString()); htw.ShiftLastIndex(ref htmlText); if (htw.CloseTagStartIndex != htw.OpenTagLastIndex + 1) { writer.WriteStartElement(htw.TagName); foreach (string attr in htw.GetAttributes()) { if (htw.TagName.Equals("img", StringComparison.OrdinalIgnoreCase) && attr.Equals("src", StringComparison.OrdinalIgnoreCase)) { string j = Path.GetFileName(htw.GetValue(attr)); writer.WriteAttributeString(attr, Path.GetFileName(htw.GetValue(attr))); if (htw.GetValue("height") == "") { SizeF sourceImageSize; SizeF imageSize; sourceImageSize = Image.FromFile(Path.Combine(Warehouse.Warehouse.AbsoluteEditorImagesDirectory, Path.GetFileName(htw.GetValue(attr)))).PhysicalDimension; imageSize = new SizeF(sourceImageSize); writer.WriteAttributeString("height", sourceImageSize.Height.ToString()); writer.WriteAttributeString("width", sourceImageSize.Width.ToString()); } } else { string j = htw.GetValue(attr); writer.WriteAttributeString(attr, htw.GetValue(attr)); } } ConvertHtmlStringToXml(htw.GetInnerHtml(), writer); htmlText = htmlText.Remove(htw.OpenTagStartIndex, htw.CloseTagLastIndex - htw.OpenTagStartIndex + 1); writer.WriteFullEndElement(); } else { htw.RemoveTag(ref htmlText); } } else { if (htmlText.Trim() != "") { writer.WriteString(htmlText); } } } while (tag.ToString() != ""); string p = ""; }
private void WriteAnnotations(TrackingAnnotationCollection annotations, XmlTextWriter writer) { if ((null == annotations) || (0 == annotations.Count)) return; writer.WriteStartElement("Annotations"); foreach (string s in annotations) { // // Preserve null and empty as distinct values // null == <Annotation /> empty string = <Annotation></Annotation> writer.WriteStartElement("Annotation"); if ((null == s) || (s.Length > 0)) { writer.WriteValue(null == s ? String.Empty : s); writer.WriteEndElement(); } else writer.WriteFullEndElement(); } writer.WriteEndElement(); }
private void SaveXmlCommandFile(string filename) { if (this.MergeListFileArray.Count < 1) { return; } System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(filename, new System.Text.UnicodeEncoding()); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("merge"); // Write sub-elements foreach (MergeListFiles mergeItem in this.MergeListFileArray) { writer.WriteStartElement("file"); if (mergeItem.Include == false) { writer.WriteAttributeString("exclude", "1"); } writer.WriteElementString("path", mergeItem.Path); writer.WriteElementString("pages", mergeItem.Pages); if (mergeItem.Bookmark != null) { writer.WriteElementString("bookmark", mergeItem.Bookmark); } if (mergeItem.Level > 0) { writer.WriteElementString("level", XmlConvert.ToString(mergeItem.Level)); } writer.WriteEndElement(); } #region write info and options if (this.MergeListInfo.HasInfo == true) { writer.WriteStartElement("info"); if (this.MergeListInfo.InfoAuthor.Length > 0) { writer.WriteElementString("author", this.MergeListInfo.InfoAuthor); } if (this.MergeListInfo.InfoSubject.Length > 0) { writer.WriteElementString("subject", this.MergeListInfo.InfoSubject); } if (this.MergeListInfo.InfoTitle.Length > 0) { writer.WriteElementString("title", this.MergeListInfo.InfoTitle); } writer.WriteEndElement(); } writer.WriteStartElement("options"); if (string.IsNullOrEmpty(this.MergeListInfo.OutFilename) == false) { writer.WriteElementString("outfile", this.MergeListInfo.OutFilename); } if (string.IsNullOrEmpty(this.MergeListInfo.Annotation) == false) { writer.WriteElementString("annotation", this.MergeListInfo.Annotation); } if (this.MergeListInfo.NumberPages == true) { writer.WriteElementString("startpage", this.MergeListInfo.StartPage.ToString()); } writer.WriteElementString("paginationformat", ((int)this.MergeListInfo.PaginationFormat).ToString()); writer.WriteEndElement(); #endregion writer.WriteFullEndElement(); writer.Close(); }