public void NewLineOnAttributes_2(XmlWriterUtils utils) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.OmitXmlDeclaration = true; wSettings.Indent = true; wSettings.NewLineOnAttributes = true; XmlWriter w = utils.CreateWriter(wSettings); CError.Compare(w.Settings.NewLineOnAttributes, true, "Mismatch in NewLineOnAttributes"); w.WriteStartElement("root"); w.WriteAttributeString("attr1", "value1"); w.WriteAttributeString("attr2", "value2"); w.WriteEndElement(); w.Dispose(); Assert.True(utils.CompareString("<root" + wSettings.NewLineChars + " attr1=\"value1\"" + wSettings.NewLineChars + " attr2=\"value2\" />")); }
public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { MemoryStream memoryStream = new MemoryStream(); XmlWriter xmlWriter = XmlWriter.Create(memoryStream, this.xmlSettings); message.WriteMessage(xmlWriter); xmlWriter.Flush(); xmlWriter.Dispose(); byte[] buffer = memoryStream.GetBuffer(); int num = (int)memoryStream.Position; memoryStream.Dispose(); int bufferSize = num + messageOffset; byte[] array = bufferManager.TakeBuffer(bufferSize); Array.Copy(buffer, 0, array, messageOffset, num); ArraySegment <byte> result = new ArraySegment <byte>(array, messageOffset, num); return(result); }
public void writeNode_XmlReader36(XmlWriterUtils utils, bool defattr) { string strxml = "<Ro\u00F6t \u00F6=\"\u00F6\" />"; string exp = strxml; XmlReader xr = CreateReader(new StringReader(strxml)); XmlWriterSettings ws = new XmlWriterSettings(); ws.OmitXmlDeclaration = true; XmlWriter w = utils.CreateWriter(ws); while (!xr.EOF) { w.WriteNode(xr, defattr); } xr.Dispose(); w.Dispose(); Assert.True(utils.CompareString(exp)); }
public void EOF_Handling_16(XmlWriterUtils utils, NewLineHandling nlHandling, string newLineChars) { XmlWriterSettings wSettings = new XmlWriterSettings(); string PrototypeOutput = "<root&NewLine foo=\"fooval\"&NewLine bar=\"barval\" />"; wSettings.NewLineHandling = nlHandling; wSettings.Indent = true; wSettings.NewLineChars = newLineChars; wSettings.NewLineOnAttributes = true; XmlWriter w = CreateMemWriter(utils, wSettings); w.WriteStartElement("root"); w.WriteAttributeString("foo", "fooval"); w.WriteAttributeString("bar", "barval"); w.WriteEndElement(); w.Dispose(); VerifyOutput(PrototypeOutput.Replace("&NewLine", newLineChars)); }
//[Variation(Desc = "16.Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; Entitize, '\uDE40\uDA72', '\uDE40\uDA72'", Params = new object[] { NewLineHandling.Entitize })] //[Variation(Desc = "17.Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; Replace, '\uDE40\uDA72', '\uDE40\uDA72'", Params = new object[] { NewLineHandling.Replace })] //[Variation(Desc = "18.Test fo proper indentation and newline handling when Indent = true, with custom NewLineChars and IndentChars; None, '\uDE40\uDA72', '\uDE40\uDA72'", Params = new object[] { NewLineHandling.None })] public int EOF_Handling_22() { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NewLineHandling = (NewLineHandling)CurVariation.Params[0]; wSettings.Indent = true; wSettings.NewLineChars = "\uDE40\uDA72"; wSettings.IndentChars = "\uDE40\uDA72"; XmlWriter w = CreateMemWriter(wSettings); try { w.WriteStartElement("root"); w.WriteStartElement("foo"); w.Dispose(); } catch (ArgumentException e) { CError.WriteLine(e.Message); return(TEST_PASS); } return(TEST_FAIL); }
public void EOF_Handling_22(XmlWriterUtils utils, NewLineHandling nlHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NewLineHandling = nlHandling; wSettings.Indent = true; wSettings.NewLineChars = "\uDE40\uDA72"; wSettings.IndentChars = "\uDE40\uDA72"; XmlWriter w = CreateMemWriter(utils, wSettings); try { w.WriteStartElement("root"); w.WriteStartElement("foo"); w.Dispose(); } catch (ArgumentException e) { CError.WriteLine(e.Message); return; } Assert.True(false); }
//[Variation(Desc = "write start element and then close when the WriteEndDocumentOnClose = false", Pri = 1, Params = new object[] { false, "<root>" })] //[Variation(Desc = "write start element and then close when the WriteEndDocumentOnClose = true", Pri = 1, Params = new object[] { true, "<root />" })] public int TestWriteEndDocumentOnCoseForOneElement() { bool writeEndDocument = (bool)CurVariation.Params[0]; string expected = (string)CurVariation.Params[1]; StringWriter output = new StringWriter(); XmlWriterSettings ws = new XmlWriterSettings(); ws.OmitXmlDeclaration = true; ws.WriteEndDocumentOnClose = writeEndDocument; XmlWriter writer = XmlWriter.Create(output, ws); writer.WriteStartElement("root"); writer.Dispose(); string act = output.ToString(); CError.Compare(act, expected, "FAILED: when one start element and WriteEndDocumentOnClose = " + ws.WriteEndDocumentOnClose + ", expected: " + expected + ", received: " + act); return(TEST_PASS); }
//[Variation(Id = 3, Desc = "Attributes of nested elements", Priority = 1)] public void NewLineOnAttributes_3() { XDocument d = new XDocument(); XmlWriter w = d.CreateWriter(); w.WriteStartElement("level1"); w.WriteAttributeString("attr1", "value1"); w.WriteAttributeString("attr2", "value2"); w.WriteStartElement("level2"); w.WriteAttributeString("attr1", "value1"); w.WriteAttributeString("attr2", "value2"); w.WriteEndElement(); w.WriteEndElement(); w.Dispose(); if (!CompareBaseline(d, "NewLineOnAttributes3.txt")) { throw new TestException(TestResult.Failed, ""); } }
public void auto_8(XmlWriterUtils utils) { XmlWriter w = utils.CreateWriter(ConformanceLevel.Auto); string strxml = "<!DOCTYPE test [<!ENTITY e 'abc'>]><Root />"; XmlReaderSettings rSettings = new XmlReaderSettings(); rSettings.CloseInput = true; rSettings.DtdProcessing = DtdProcessing.Parse; XmlReader xr = ReaderHelper.Create(new StringReader(strxml), rSettings, (string)null); CError.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Auto, "Error"); xr.Read(); CError.Compare(xr.NodeType.ToString(), "DocumentType", "Error"); w.WriteNode(xr, false); CError.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error"); w.Dispose(); xr.Dispose(); return; }
public void Save <T>(T t) { XmlSerializer xs = new XmlSerializer(typeof(T)); MemoryStream stream = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineChars = "\r\n"; using (XmlWriter writer = XmlWriter.Create(_xml, settings)) { var xns = new XmlSerializerNamespaces(); xns.Add(string.Empty, string.Empty); //去除默认命名空间 xs.Serialize(writer, t, xns); writer.Close(); writer.Dispose(); } }
public void Dispose() { if (writer != null) { #if !WINDOWS_UWP writer.Close(); #else writer.Dispose(); #endif writer = null; } if (stream != null) { #if !WINDOWS_UWP stream.Close(); #endif stream.Dispose(); stream = null; } }
public void CloseOutput_1(XmlWriterUtils utils, string outputType) { XmlWriterSettings wSettings = new XmlWriterSettings(); XmlWriter w = null; switch (utils.WriterType) { case WriterType.UTF8Writer: wSettings.Encoding = Encoding.UTF8; break; case WriterType.UnicodeWriter: wSettings.Encoding = Encoding.Unicode; break; } Stream writerStream = new MemoryStream(); switch (outputType) { case "Stream": w = WriterHelper.Create(writerStream, wSettings, overrideAsync: true, async: utils.Async); break; case "Textwriter": StreamWriter tw = new StreamWriter(writerStream, wSettings.Encoding); w = WriterHelper.Create(tw, wSettings, overrideAsync: true, async: utils.Async); break; } w.WriteStartElement("root"); w.WriteEndElement(); w.Dispose(); if (writerStream.CanWrite) { writerStream.Dispose(); return; } CError.WriteLine("Error: XmlWriter closed the stream when CloseOutput = false"); Assert.True(false); }
//[Variation(Id = 2, Desc = "Change to CL Document after WriteStartDocument(standalone = true)", Priority = 0, Param = "true")] //[Variation(Id = 3, Desc = "Change to CL Document after WriteStartDocument(standalone = false)", Priority = 0, Param = "false")] public void auto_2() { XDocument d = new XDocument(); XmlWriter w = d.CreateWriter(); switch (Variation.Param.ToString()) { case "true": w.WriteStartDocument(true); break; case "false": w.WriteStartDocument(false); break; } // PROLOG TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error"); w.WriteStartElement("root"); // ELEMENT CONTENT TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error"); // Inside Attribute w.WriteStartAttribute("attr"); TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error"); w.WriteEndElement(); // Try writing another root element, should error try { w.WriteStartElement("root"); } catch (InvalidOperationException) { return; } finally { w.Dispose(); } TestLog.WriteLine("Conformance level = Document did not take effect"); throw new TestException(TestResult.Failed, ""); }
public static CamlQuery CreateAllItemsQuery(int rowLimit, params string[] viewFields) { if (rowLimit <= 0) { throw new ArgumentOutOfRangeException("rowLimit"); } if (viewFields == null) { throw new ArgumentNullException("viewFields"); } CamlQuery camlQuery = new CamlQuery(); StringBuilder stringBuilder = new StringBuilder(); XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, new XmlWriterSettings { OmitXmlDeclaration = true }); xmlWriter.WriteStartElement("View"); xmlWriter.WriteAttributeString("Scope", "RecursiveAll"); if (viewFields.Length > 0) { xmlWriter.WriteStartElement("ViewFields"); for (int i = 0; i < viewFields.Length; i++) { string value = viewFields[i]; if (!string.IsNullOrEmpty(value)) { xmlWriter.WriteStartElement("FieldRef"); xmlWriter.WriteAttributeString("Name", value); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } xmlWriter.WriteElementString("RowLimit", rowLimit.ToString(CultureInfo.InvariantCulture)); xmlWriter.WriteEndElement(); //Edited for .NET Core xmlWriter.Dispose();//.Close(); camlQuery.ViewXml = stringBuilder.ToString(); return(camlQuery); }
/// <summary> /// Returns the schema for the specified type (returns the entire schema if null). /// </summary> public override string GetSchema(string typeName) { XmlWriterSettings settings = Utils.DefaultXmlWriterSettings(); MemoryStream ostrm = new MemoryStream(); XmlWriter writer = XmlWriter.Create(ostrm, settings); try { if (typeName == null || m_schema.Elements.Values.Count == 0) { m_schema.Write(writer); } else { foreach (XmlSchemaObject current in m_schema.Elements.Values) { XmlSchemaElement element = current as XmlSchemaElement; if (element != null) { if (element.Name == typeName) { XmlSchema schema = new XmlSchema(); schema.Items.Add(element.ElementSchemaType); schema.Items.Add(element); schema.Write(writer); break; } } } } } finally { writer.Flush(); writer.Dispose(); } return(new UTF8Encoding().GetString(ostrm.ToArray())); }
public void CloseOutput_2(XmlWriterUtils utils, bool closeOutput) { XmlWriterSettings wSettings = new XmlWriterSettings(); switch (utils.WriterType) { case WriterType.UTF8Writer: wSettings.Encoding = Encoding.UTF8; break; case WriterType.UnicodeWriter: wSettings.Encoding = Encoding.Unicode; break; } wSettings.CloseOutput = closeOutput; XmlWriter w = WriterHelper.Create("writer.out", wSettings, overrideAsync: true, async: utils.Async); w.WriteStartElement("root"); w.WriteEndElement(); w.Dispose(); // Check if you can open the file in ReadWrite mode Stream fs = null; try { fs = FilePathUtil.getStream("writer.out");/*new FileStream("writer.out", FileMode.Open, FileAccess.ReadWrite);*/ } catch (Exception e) { CError.WriteLineIgnore("Exception: " + e.ToString()); CError.WriteLine("Uri stream is not closed by writer"); Assert.True(false); } finally { fs.Dispose(); } return; }
public static string GetString(this XmlDocument xmlDocument) { if (xmlDocument == null) { throw new ArgumentNullException(nameof(xmlDocument)); } var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false, false), Indent = true, OmitXmlDeclaration = false }; string output; StringWriterExtended textWriter = null; XmlWriter xmlWriter = null; try { textWriter = new StringWriterExtended(Encoding.UTF8, CultureInfo.InvariantCulture); xmlWriter = XmlWriter.Create(textWriter, settings); xmlDocument.Save(textWriter); output = textWriter.ToString(); } finally { if (xmlWriter != null) { #if NET45_OR_GREATER xmlWriter.Dispose(); #endif } else { textWriter?.Dispose(); } } return(output); }
/// <summary> /// Asynchronously creates the XML reader. /// </summary> /// <returns> /// A <see cref="Task"/> that represents the asynchronous create reader operation. /// </returns> private Task CreateXmlAsync() { _current = new XDocument(); if (_reader != null) { _reader.Dispose(); } if (_writer != null) { _writer.Dispose(); } _reader = XmlReader.Create(_stream, new XmlReaderSettings() { Async = true, CheckCharacters = true, CloseInput = false, ConformanceLevel = ConformanceLevel.Document, DtdProcessing = DtdProcessing.Prohibit, IgnoreComments = true, IgnoreWhitespace = true, IgnoreProcessingInstructions = true }); _writer = XmlWriter.Create(_stream, new XmlWriterSettings() { Async = true, CheckCharacters = true, CloseOutput = false, ConformanceLevel = ConformanceLevel.Document, Indent = false, NamespaceHandling = NamespaceHandling.OmitDuplicates, NewLineOnAttributes = false, OmitXmlDeclaration = false, WriteEndDocumentOnClose = false, Encoding = new UTF8Encoding(false) }); return(_client.OnStreamResetAsync()); }
public static void Serialize <T>(string filePath, T obj, params Type[] additionalTypes) { XmlWriter writer = XmlWriter.Create(new FileStream(filePath, FileMode.Create, FileAccess.Write), WriteSettings); try { DataContractSerializer serializer = new DataContractSerializer(typeof(T), additionalTypes); serializer.WriteObject(writer, obj); } catch (Exception e) { Log4NetService.Instance.GetLogger <MainWindow>().Error("An error occurred while saving the " + $"{typeof(T).FullName}", e); MessageBox.Show("Saving error", "Something went wrong", MessageBoxButton.OK, MessageBoxImage.Error); } finally { writer.Dispose(); } }
public void indent_17(XmlWriterUtils utils) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.OmitXmlDeclaration = true; wSettings.Indent = true; XmlWriter w = utils.CreateWriter(wSettings); w.WriteStartElement("e1"); w.WriteStartElement("e2"); w.WriteStartElement("e3"); w.WriteStartElement("e4"); w.WriteFullEndElement(); w.WriteFullEndElement(); w.WriteFullEndElement(); w.WriteFullEndElement(); w.Dispose(); CError.Compare(utils.CompareString("<e1>" + wSettings.NewLineChars + " <e2>" + wSettings.NewLineChars + " <e3>" + wSettings.NewLineChars + " <e4></e4>" + wSettings.NewLineChars + " </e3>" + wSettings.NewLineChars + " </e2>" + wSettings.NewLineChars + "</e1>"), ""); return; }
//[Variation(Desc = "Check for tab character in attribute with 'Entitize'", Param = NewLineHandling.Entitize, Id = 26, Priority = 0)] //[Variation(Desc = "Check for tab character in attribute with 'Replace'", Param = NewLineHandling.Replace, Id = 27, Priority = 0)] //[Variation(Desc = "Check for tab character in attribute with 'None'", Param = NewLineHandling.None, Id = 28, Priority = 0)] public void EOF_Handling_10() { string Tabs = "foo\tbar	foo\n\tbar\t\n\t"; XDocument d = new XDocument(); XmlWriter w = CreateWriter(d); w.WriteStartElement("root"); w.WriteStartAttribute("foo"); w.WriteString("foo\tbar"); w.WriteCharEntity('\t'); w.WriteString("foo\n\tbar\t\n\t"); w.WriteEndAttribute(); w.WriteEndElement(); w.Dispose(); if (!CompareReader(d, "<root foo=\"" + ExpectedOutput(Tabs, (NewLineHandling)Variation.Param, true) + "\" />")) { throw new TestException(TestResult.Failed, ""); } }
public void Store(string FilePath) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; XmlWriter writer = XmlWriter.Create(FilePath, settings); writer.WriteStartDocument(); writer.WriteStartElement("ControlPresets"); foreach (PresetGroup preset in Presets.Values) { preset.Store(writer); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Dispose(); }
public ClientActionSetProperty(ClientObject obj, string propName, object propValue) : base(ClientRuntimeContext.GetContextFromClientObject(obj), (obj == null) ? null : obj.Path, propName) { if (obj == null) { throw new ArgumentNullException("obj"); } if (obj.Path == null || !obj.Path.IsValid) { throw new ClientRequestException(Resources.GetString("NoObjectPathAssociatedWithObject")); } ClientAction.CheckActionParameterInContext(obj.Context, propValue); this.m_propName = propName; this.m_propValue = propValue; this.m_serializationContext = new SerializationContext(obj.Context); this.m_sb = new ChunkStringBuilder(); XmlWriter xmlWriter = this.m_sb.CreateXmlWriter(); this.WriteToXmlPrivate(xmlWriter, this.m_serializationContext); xmlWriter.Dispose();//.Close(); this.m_propValue = null; }
public void element_10c(XmlWriterUtils utils) { XmlWriter w = utils.CreateWriter(); w.WriteDocType("a", null, null, "<!ATTLIST Root a (val|value) \"val\">"); w.WriteStartElement("Root"); for (int i = 0; i < 200; i++) { w.WriteAttributeString("p", "a", "n" + i, "val"); } try { w.WriteAttributeString("p", "a", "n" + 199, "val"); } catch (XmlException) { return; } finally { w.Dispose(); } Assert.True(false); }
public override void Close() { if (_writer != null) { try { _writer.Flush(); } finally { try { _writer.Dispose(); } finally { _writer = null; } } } }
public void EOF_Handling_11(XmlWriterUtils utils, NewLineHandling nlHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NewLineHandling = nlHandling; wSettings.Indent = true; XmlWriter w = CreateMemWriter(utils, wSettings); CError.Compare(w.Settings.NewLineChars, Environment.NewLine, "Incorrect default value for XmlWriter.Settings.NewLineChars"); CError.Compare(w.Settings.IndentChars, " ", "Incorrect default value for XmlWriter.Settings.IndentChars"); w.WriteStartElement("root"); w.WriteStartElement("foo"); w.WriteElementString("bar", ""); w.WriteEndElement(); w.WriteEndElement(); w.Dispose(); VerifyOutput(string.Format("<root>{0} <foo>{0} <bar />{0} </foo>{0}</root>", Environment.NewLine)); }
public async void Write(string path) { IFile file = await FileSystem.Current.LocalStorage.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting); XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = true; XmlWriter writer = XmlWriter.Create(await file.OpenAsync(FileAccess.ReadAndWrite), settings); writer.WriteStartDocument(); writer.WriteStartElement("Tasks"); for (int i = 0; i < tasks.Count; i++) { tasks[i].WriteXML(writer); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Dispose(); }
public void EOF_Handling_06(XmlWriterUtils utils, NewLineHandling nlHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); string Tabs = "foo\tbar	foo\n\tbar\t\n\t"; wSettings.NewLineHandling = nlHandling; XmlWriter w = CreateMemWriter(utils, wSettings); w.WriteStartElement("root"); w.WriteString("foo\tbar"); w.WriteCharEntity('\t'); w.WriteString("foo\n\tbar\t\n\t"); w.WriteEndElement(); w.Dispose(); VerifyOutput("<root>" + ExpectedOutput(Tabs, nlHandling, false) + "</root>"); return; }
//[Variation(Desc = "Check for tab character in element with 'Entitize'", Param = NewLineHandling.Entitize, id = 14, Pri = 0)] //[Variation(Desc = "Check for tab character in element with 'Replace'", Param = NewLineHandling.Replace, id = 15, Pri = 0)] //[Variation(Desc = "Check for tab character in element with 'None'", Param = NewLineHandling.None, id = 16, Pri = 0)] public int EOF_Handling_06() { XmlWriterSettings wSettings = new XmlWriterSettings(); string Tabs = "foo\tbar	foo\n\tbar\t\n\t"; wSettings.NewLineHandling = (NewLineHandling)CurVariation.Param; XmlWriter w = CreateMemWriter(wSettings); w.WriteStartElement("root"); w.WriteString("foo\tbar"); w.WriteCharEntity('\t'); w.WriteString("foo\n\tbar\t\n\t"); w.WriteEndElement(); w.Dispose(); VerifyOutput("<root>" + ExpectedOutput(Tabs, (NewLineHandling)CurVariation.Param, false) + "</root>"); return(TEST_PASS); }
public NSAttributedString ToAttributedString() { xmlWriter.WriteEndElement(); // body xmlWriter.WriteEndElement(); // html xmlWriter.Flush(); if (text == null || text.Length == 0) { return(new NSAttributedString(String.Empty)); } NSDictionary docAttributes; try { return(CreateStringFromHTML(text.ToString(), out docAttributes)); } finally { text = null; xmlWriter.Dispose(); xmlWriter = null; docAttributes = null; } }
private bool Diff() { bool flag = false; XmlWriterSettings xws = new XmlWriterSettings(); xws.ConformanceLevel = ConformanceLevel.Auto; xws.CheckCharacters = false; _Writer = XmlWriter.Create(new StringWriter(_Output), xws); _Writer.WriteStartElement(String.Empty, "Root", String.Empty); flag = CompareChildren(this._SourceDoc, this._TargetDoc); _Writer.WriteEndElement(); _Writer.Dispose(); return flag; }
// base for following methods private static void WriteElement(XmlWriter writer, string prefix, string localName, string namespaceURI, string value) { writer.WriteStartElement(prefix, localName, namespaceURI); if (value != null) { writer.WriteString(value); } writer.WriteEndElement(); writer.Dispose(); }