public ChorusNotesMergeEventListener(string path) { _path = path; try { if (!File.Exists(path)) { var doc = new XmlDocument(); doc.LoadXml(string.Format("<notes version='{0}'/>", FormatVersionNumber.ToString())); using (var fileWriter = XmlWriter.Create(path, CanonicalXmlSettings.CreateXmlWriterSettings())) { doc.Save(fileWriter); } } } catch (Exception error) { Debug.Fail("Something went wrong trying to create a blank ChorusNotes file :" + error.Message); //todo log that the xml was the wrong format } _tempFile = new TempFile(); _readerStream = new FileStream(path, FileMode.Open); _reader = XmlReader.Create(_readerStream, CanonicalXmlSettings.CreateXmlReaderSettings()); _writer = XmlWriter.Create(_tempFile.Path, CanonicalXmlSettings.CreateXmlWriterSettings()); StreamToInsertionPoint(_reader, _writer); }
public void WriteNodeShallow_WithMultipleChildren_VisitsThemAll() { const string xml = @"<?xml version='1.0' encoding='utf-8'?> <root attrib='1'> <child>some child</child> <child>some child</child> </root>"; var output = new StringBuilder(); using (var reader = new StringReader(xml)) using (var writer = new StringWriter(output)) { var xmlReader = XmlReader.Create(reader); var xmlWriter = XmlWriter.Create(writer, CanonicalXmlSettings.CreateXmlWriterSettings()); int count = 0; while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "child") { count++; } xmlWriter.WriteNodeShallow(xmlReader); } Assert.That(count, Is.EqualTo(2)); } }
private static void CarefullyWriteOutResultingXml(HtmlFileForMerging oursXml, NodeMergeResult result) { //REVIEW: it's not clear whether we need all this fancy xml cannonicalization, when we're going to run //it through html tidy to make html anyhow. This is just from the code we copied from. //Note it also is doing something careful with unicode. using (var writer = XmlWriter.Create(oursXml.GetPathToXHtml(), CanonicalXmlSettings.CreateXmlWriterSettings())) { var nameSpaceManager = new XmlNamespaceManager(new NameTable()); //nameSpaceManager.AddNamespace("palaso", "urn://palaso.org/ldmlExtensions/v1"); var readerSettings = new XmlReaderSettings { NameTable = nameSpaceManager.NameTable, IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Auto, ValidationType = ValidationType.None, XmlResolver = null, CloseInput = true, DtdProcessing = DtdProcessing.Prohibit, }; using ( var nodeReader = XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes(result.MergedNode.OuterXml)), readerSettings)) { writer.WriteNode(nodeReader, false); } } }
/// <summary> /// Do a 3-file merge, placing the result over the "ours" file and returning an error status /// </summary> /// <remarks>Implementations can exit with an exception, which the caller will catch and deal with. /// The must not have any UI, no interaction with the user.</remarks> public void Do3WayMerge(MergeOrder mergeOrder) { if (mergeOrder == null) { throw new ArgumentNullException("mergeOrder"); } bool addedCollationAttr; PreMergeFile(mergeOrder, out addedCollationAttr); var merger = new XmlMerger(mergeOrder.MergeSituation); SetupElementStrategies(merger); merger.EventListener = mergeOrder.EventListener; XmlMergeService.RemoveAmbiguousChildNodes = true; var result = merger.MergeFiles(mergeOrder.pathToOurs, mergeOrder.pathToTheirs, mergeOrder.pathToCommonAncestor); using (var writer = XmlWriter.Create(mergeOrder.pathToOurs, CanonicalXmlSettings.CreateXmlWriterSettings())) { var readerSettings = CanonicalXmlSettings.CreateXmlReaderSettings(ConformanceLevel.Auto); readerSettings.XmlResolver = null; readerSettings.ProhibitDtd = false; using (var nodeReader = XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes(result.MergedNode.OuterXml)), readerSettings)) { writer.WriteNode(nodeReader, false); } } }
internal static void WriteNestedFile(string newPathname, XmlNode root) { using (var writer = XmlWriter.Create(newPathname, CanonicalXmlSettings.CreateXmlWriterSettings())) { XmlUtils.WriteNode(writer, root.OuterXml, new HashSet <string>()); } }
public void Write(WritingSystemChangeLog log) { if (log == null) { throw new ArgumentNullException("log"); } if (!File.Exists(FilePath)) { string logDirectory = Path.GetDirectoryName(FilePath); Directory.CreateDirectory(logDirectory); } using (var streamWriter = new StreamWriter(FilePath)) { using (var writer = XmlWriter.Create(streamWriter, CanonicalXmlSettings.CreateXmlWriterSettings())) { writer.WriteStartDocument(); writer.WriteStartElement("WritingSystemChangeLog"); writer.WriteAttributeString("Version", log.Version); writer.WriteStartElement("Changes"); WriteChanges(writer, log); writer.WriteEndElement(); // Changes writer.WriteEndElement(); // WritingSystemChangeLog writer.Close(); } } }
// public void SaveAs(string path) // { // _doc.Save(path); // } public void Save(IProgress progress) { try { if (string.IsNullOrEmpty(AnnotationFilePath)) { throw new InvalidOperationException( "Cannot save if the repository was created from a string"); } progress.WriteStatus("Saving Chorus Notes..."); _writingFileOurselves = true; using (var writer = XmlWriter.Create(AnnotationFilePath, CanonicalXmlSettings.CreateXmlWriterSettings()) ) { _doc.Save(writer); } progress.WriteStatus(""); _isDirty = false; UpateAnnotationFileWriteTime(); } catch (Exception e) { SIL.Reporting.ErrorReport.NotifyUserOfProblem(e, "Chorus has a problem saving notes for {0}.", _annotationFilePath); } finally { _writingFileOurselves = false; } }
/// <summary> /// Find any .NewChorusNotes files which were created by the MergeChorus.exe and either rename them to .ChorusNotes /// or add any annotations found in them to the existing .ChorusNotes file. /// </summary> private static void AppendAnyNewNotes(string localRepositoryPath) { var allNewNotes = Directory.GetFiles(localRepositoryPath, "*.NewChorusNotes", SearchOption.AllDirectories); foreach (var newNote in allNewNotes) { var oldNotesFile = newNote.Replace("NewChorusNotes", "ChorusNotes"); if (File.Exists(oldNotesFile)) { // Add new annotations to the end of any which were in the repo var oldDoc = new XmlDocument(); oldDoc.Load(oldNotesFile); var oldNotesNode = oldDoc.SelectSingleNode("/notes"); var newDoc = new XmlDocument(); newDoc.Load(newNote); var newAnnotations = newDoc.SelectNodes("/notes/annotation"); foreach (XmlNode node in newAnnotations) { var newOldNode = oldDoc.ImportNode(node, true); oldNotesNode.AppendChild(newOldNode); } using (var fileWriter = XmlWriter.Create(oldNotesFile, CanonicalXmlSettings.CreateXmlWriterSettings())) { oldDoc.Save(fileWriter); } File.Delete(newNote); } else { // There was no former ChorusNotes file, so just rename File.Move(newNote, oldNotesFile); } } }
public void ReplaceWritingSystemId(string oldId, string newId) { if (XmlDoc.SelectSingleNode("/optionsList") != null) { var formCollections = XmlDoc.SelectNodes("//option/name").Cast <XmlNode>().Concat( XmlDoc.SelectNodes("//option/abbreviation").Cast <XmlNode>()).Concat( XmlDoc.SelectNodes("//option/description").Cast <XmlNode>()); foreach (XmlNode nameNode in formCollections) { var formNodes = nameNode.SelectNodes(".//form").Cast <XmlNode>(); var formWithOldId = formNodes.SingleOrDefault(node => node.Attributes["lang"].Value == oldId); if (formWithOldId != null) { if (formNodes.Any(node => node.Attributes["lang"].Value == newId)) { nameNode.RemoveChild(formWithOldId); } else { formWithOldId.Attributes["lang"].Value = newId; } } } var canonicalWriter = XmlWriter.Create(_optionListFilePath, CanonicalXmlSettings.CreateXmlWriterSettings()); XmlDoc.Save(canonicalWriter); canonicalWriter.Close(); } }
internal static void WriteNestedFile(string newPathname, XElement root) { using (var writer = XmlWriter.Create(newPathname, CanonicalXmlSettings.CreateXmlWriterSettings())) { writer.WriteStartDocument(); WriteElement(writer, root); } }
//private static void WriteProblemDataFile(string pathname, XmlNode data) //{ // var doc = data.OwnerDocument; // doc.Save(pathname); //} private static void WriteProblemDataFile(string pathname, byte[] data) { using (var reader = XmlReader.Create(new MemoryStream(data, false), CanonicalXmlSettings.CreateXmlReaderSettings())) using (var writer = XmlWriter.Create(pathname, CanonicalXmlSettings.CreateXmlWriterSettings())) { writer.WriteNode(reader, true); } }
private static void PrintNodeToConsole(XmlNode node) { var writer = XmlWriter.Create(Console.Out, CanonicalXmlSettings.CreateXmlWriterSettings(ConformanceLevel.Fragment)); node.WriteContentTo(writer); writer.Flush(); Console.WriteLine(); }
public void ExistingUnusedLdml_Write_PreservesData() { var sw = new StringWriter(); var ws = new WritingSystemDefinition("en"); var writer = XmlWriter.Create(sw, CanonicalXmlSettings.CreateXmlWriterSettings()); _adaptor.Write(writer, ws, XmlReader.Create(new StringReader("<ldml><!--Comment--><dates/><special>hey</special></ldml>"))); writer.Close(); AssertThatXmlIn.String(sw.ToString()).HasAtLeastOneMatchForXpath("/ldml/special[text()=\"hey\"]"); }
public void SaveNow() { using (var writer = XmlWriter.Create(_dataFilePath, CanonicalXmlSettings.CreateXmlWriterSettings())) { writer.WriteStartElement("shopping"); WriteArea(writer, _area1Label.Text, _area1Text.Text); WriteArea(writer, _area2Label.Text, _area2Text.Text); writer.WriteEndElement(); } }
public LiftWriter(StringBuilder builder, bool produceFragmentOnly) : this() { _writer = XmlWriter.Create(builder, CanonicalXmlSettings.CreateXmlWriterSettings( produceFragmentOnly ? ConformanceLevel.Fragment : ConformanceLevel.Document) ); if (!produceFragmentOnly) { Start(); } }
public void Write(TextReader pliftReader, TextWriter textWriter) { using (_writer = XmlWriter.Create(textWriter, CanonicalXmlSettings.CreateXmlWriterSettings())) { // _writer.WriteProcessingInstruction("xml-stylesheet", @"type='text/css' href='dictionary.css"); _writer.WriteRaw("<!DOCTYPE HTML>"); _writer.WriteStartElement("html"); _writer.WriteStartElement("head"); _writer.WriteStartElement("meta"); _writer.WriteAttributeString("charset", "UTF-8"); // _writer.WriteAttributeString("http-equiv", "content-type"); // _writer.WriteAttributeString("content","text/html; charset=utf-8"); _writer.WriteEndElement(); // Note: WriteRaw will not write chorus compliant formatting. Use WriteNode instead. CP 2011-01 //jh: Cambell, exported stuff shouldn't be part of chorus send/receive. if (_linkToUserCss) { _writer.WriteRaw("<LINK rel='stylesheet' href='autoLayout.css' type='text/css' />"); _writer.WriteRaw("<LINK rel='stylesheet' href='autoFonts.css' type='text/css' />"); _writer.WriteRaw("<LINK rel='stylesheet' href='customLayout.css' type='text/css' />"); _writer.WriteRaw("<LINK rel='stylesheet' href='customFonts.css' type='text/css' />"); } _writer.WriteEndElement(); _writer.WriteStartElement("body"); WriteClassAttr("dicBody"); var doc = new XPathDocument(pliftReader); var navigator = doc.CreateNavigator(); var entryIterator = navigator.Select("//entry"); foreach (XPathNavigator entryNav in entryIterator) { XPathNavigator headwordFieldNode = entryNav.SelectSingleNode("field[@type='headword']"); if (headwordFieldNode == null || string.IsNullOrEmpty(headwordFieldNode.Value)) { continue; } AddLetterSectionIfNeeded(headwordFieldNode.Value); StartDiv("entry"); OutputNonSenseFieldsOfEnry(entryNav); DoSenses(entryNav.Select("sense"), headwordFieldNode); EndDiv(); //entry } if (_currentLetterGroup != string.Empty) { EndDiv(); //the last letHead div} EndDiv(); //the last letData div } _writer.WriteEndElement(); //body _writer.WriteEndElement(); //html } }
/// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="includeByteOrderMark">PrinceXML (at least v7 chokes if given a BOM, Lexique Pro chokes without it) </param> public LiftWriter(string path, ByteOrderStyle byteOrderStyle) : this() { _disposed = true; // Just in case we throw in the constructor var settings = CanonicalXmlSettings.CreateXmlWriterSettings(); settings.Encoding = new UTF8Encoding(byteOrderStyle == ByteOrderStyle.BOM); _writer = XmlWriter.Create(path, settings); Start(); _disposed = false; }
private static void DoPostMerge(string outputPath, XmlNode mergedNode) { foreach (XmlNode partNode in mergedNode.SafeSelectNodes("layout/generate")) { partNode.Attributes.Remove(partNode.Attributes["combinedkey"]); } using (var writer = XmlWriter.Create(outputPath, CanonicalXmlSettings.CreateXmlWriterSettings())) { writer.WriteNode(mergedNode.CreateNavigator(), true); } }
public void WriteSetsRequiresValidTagToTrue() { var ws = new WritingSystemDefinition(); ws.RequiresValidTag = false; ws.Language = "Kalaba"; var sw = new StringWriter(); var writer = XmlWriter.Create(sw, CanonicalXmlSettings.CreateXmlWriterSettings()); Assert.Throws(typeof(ValidationException), () => _adaptor.Write(writer, ws, null)); }
private static string MakeXmlFromInventory() { ViewTemplate f = MakeSampleInventory(); var builder = new StringBuilder(); var writer = XmlWriter.Create(builder, CanonicalXmlSettings.CreateXmlWriterSettings()); f.Write(writer); writer.Close(); return(builder.ToString()); }
public void DeserializeInvAndLoadBackIn() { var writer = XmlWriter.Create(_path, CanonicalXmlSettings.CreateXmlWriterSettings()); MakeSampleInventory().Write(writer); writer.Close(); var f = new ViewTemplate(); f.Load(_path); Assert.IsNotNull(f); CheckInventoryMatchesDefinitionInResource(f); }
private static void CreateEmptyChorusNotesFile(string path) { if (!File.Exists(path)) { var doc = new XmlDocument(); doc.LoadXml(string.Format("<notes version='{0}'/>", FormatVersionNumber.ToString())); using (var fileWriter = XmlWriter.Create(path, CanonicalXmlSettings.CreateXmlWriterSettings())) { doc.Save(fileWriter); } } }
/// <summary> /// Export the contents of the lift lexicon. /// </summary> /// <returns>the name of the exported LIFT file if successful, or null if an error occurs.</returns> /// <remarks> /// This method is called in a thread, during the export process. /// </remarks> private object ExportLiftLexicon(IProgress progressDialog, params object[] parameters) { try { var projectFolder = Cache.ProjectId.ProjectFolder; var liftProjectDir = GetLiftRepositoryFolderFromFwProjectFolder(projectFolder); var liftPathname = _liftPathname; if (!Directory.Exists(liftProjectDir)) { Directory.CreateDirectory(liftProjectDir); } if (liftPathname == null) { liftPathname = Path.Combine(liftProjectDir, Cache.ProjectId.Name + ".lift"); } var outPath = liftPathname + ".tmp"; progressDialog.Message = String.Format(ResourceHelper.GetResourceString("kstidExportingEntries"), Cache.LangProject.LexDbOA.Entries.Count()); progressDialog.Minimum = 0; progressDialog.Maximum = Cache.ServiceLocator.GetInstance <ILexEntryRepository>().Count; progressDialog.Position = 0; progressDialog.AllowCancel = false; var exporter = new LiftExporter(Cache); exporter.UpdateProgress += OnDumperUpdateProgress; exporter.SetProgressMessage += OnDumperSetProgressMessage; exporter.ExportPicturesAndMedia = true; using (TextWriter textWriter = new StreamWriter(outPath)) { exporter.ExportLift(textWriter, Path.GetDirectoryName(outPath)); } //Output the Ranges file var pathWithFilename = outPath.Substring(0, outPath.Length - @".lift.tmp".Length); var outPathRanges = Path.ChangeExtension(pathWithFilename, @"lift-ranges"); using (var stringWriter = new StringWriter(new StringBuilder())) { exporter.ExportLiftRanges(stringWriter); using (var xmlWriter = XmlWriter.Create(outPathRanges, CanonicalXmlSettings.CreateXmlWriterSettings())) { var doc = new XmlDocument(); doc.LoadXml(stringWriter.ToString()); doc.WriteContentTo(xmlWriter); } return(outPath); } } catch { return(null); } }
internal static void WriteCustomPropertyFile(string newPathname, XElement element) { if (element == null) { // Still write out file with just the root element. WriteNestedFile(newPathname, new XElement(SharedConstants.AdditionalFieldsTag)); } else { using (var writer = XmlWriter.Create(newPathname, CanonicalXmlSettings.CreateXmlWriterSettings())) WriteElement(writer, element); } }
public static TempFile CreateXmlFileWithContents(string fileName, TemporaryFolder folder, string xmlBody) { string path = folder.Combine(fileName); using (var reader = XmlReader.Create(new StringReader(xmlBody))) { using (var writer = XmlWriter.Create(path, CanonicalXmlSettings.CreateXmlWriterSettings())) { writer.WriteStartDocument(); writer.WriteNode(reader, false); } } return(new TempFile(path, true)); }
public void ExportInDesignXml(string path) { var pathToXnDesignXslt = FileLocator.GetFileDistributedWithApplication("xslts", "BloomXhtmlToDataForMergingIntoInDesign.xsl"); #if DEBUG _bookSelection.CurrentSelection.OurHtmlDom.RawDom.Save(path.Replace(".xml", ".xhtml")); #endif var dom = _bookSelection.CurrentSelection.OurHtmlDom.ApplyXSLT(pathToXnDesignXslt); using (var writer = XmlWriter.Create(path, CanonicalXmlSettings.CreateXmlWriterSettings())) { dom.Save(writer); } }
/// <summary> /// Do a 3-file merge, placing the result over the "ours" file and returning an error status /// </summary> /// <remarks>Implementations can exit with an exception, which the caller will catch and deal with. /// The must not have any UI, no interaction with the user.</remarks> public void Do3WayMerge(MergeOrder mergeOrder) { if (mergeOrder == null) { throw new ArgumentNullException("mergeOrder"); } bool addedCollationAttr; PreMergeFile(mergeOrder, out addedCollationAttr); var merger = new XmlMerger(mergeOrder.MergeSituation); SetupElementStrategies(merger); merger.EventListener = mergeOrder.EventListener; XmlMergeService.RemoveAmbiguousChildNodes = true; var result = merger.MergeFiles(mergeOrder.pathToOurs, mergeOrder.pathToTheirs, mergeOrder.pathToCommonAncestor); using (var writer = XmlWriter.Create(mergeOrder.pathToOurs, CanonicalXmlSettings.CreateXmlWriterSettings())) { var nameSpaceManager = new XmlNamespaceManager(new NameTable()); nameSpaceManager.AddNamespace("palaso", "urn://palaso.org/ldmlExtensions/v1"); nameSpaceManager.AddNamespace("palaso2", "urn://palaso.org/ldmlExtensions/v2"); nameSpaceManager.AddNamespace("fw", "urn://fieldworks.sil.org/ldmlExtensions/v1"); nameSpaceManager.AddNamespace("sil", "urn://www.sil.org/ldml/0.1"); var readerSettings = CanonicalXmlSettings.CreateXmlReaderSettings(ConformanceLevel.Auto); readerSettings.NameTable = nameSpaceManager.NameTable; readerSettings.XmlResolver = null; readerSettings.ProhibitDtd = false; if (addedCollationAttr) { // Remove the optional 'key' attr we added. var adjustedCollation = result.MergedNode.SelectSingleNode("collations") .SelectNodes("collation") .Cast <XmlNode>().FirstOrDefault(collation => collation.Attributes["type"].Value == "standard"); if (adjustedCollation != null) { adjustedCollation.Attributes.Remove(adjustedCollation.Attributes["type"]); } } using (var nodeReader = XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes(result.MergedNode.OuterXml)), readerSettings)) { writer.WriteNode(nodeReader, false); } } }
public static string ToCanonicalStringFragment(string inputXml) { var builder = new StringBuilder(); var readerSettings = new XmlReaderSettings { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Fragment }; using (var reader = XmlReader.Create(new StringReader(inputXml), readerSettings)) { using (var writer = XmlWriter.Create(builder, CanonicalXmlSettings.CreateXmlWriterSettings(ConformanceLevel.Fragment))) { writer.WriteNode(reader, false); } } return(builder.ToString()); }
public void WriteReadWithBuilder_WithCanonicalXmlWriterSettings_MatchesExpected() { string xmlInput = @"<a attrib1='value1' attrib2='value2'><b>Content</b></a>".Replace('\'', '"'); const string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<a\r\n\tattrib1=\"value1\"\r\n\tattrib2=\"value2\">\r\n\t<b>Content</b>\r\n</a>"; // Note that a StringBuilder forces the stream to be 16 bit, so the output is force to utf-16. var builder = new StringBuilder(); using (var reader = XmlReader.Create(new StringReader(xmlInput))) { using (var writer = XmlWriter.Create(builder, CanonicalXmlSettings.CreateXmlWriterSettings())) { writer.WriteNode(reader, false); } } Assert.AreEqual(expected, builder.ToString()); }
public void Write_WithCanonicalXmlWriterSettingsNoNormalize_KeepLineEndings() { const string content = "\nContent\rmore\r\nOther\n\rfinal"; const string expected = "<a>" + content + "</a>"; var bldr = new StringBuilder(); using (var writer = XmlWriter.Create(bldr, CanonicalXmlSettings.CreateXmlWriterSettings(ConformanceLevel.Fragment, NewLineHandling.None))) { writer.WriteStartElement("a"); writer.WriteRaw(content); writer.WriteEndElement(); } var result = bldr.ToString(); Console.WriteLine(result); Assert.AreEqual(expected, result); }