private void button2_Click(object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); //To create the XML DOM Tree doc.Load(@"D:\MS.Net\CSharp\XMLParser\XMLParser\Emp.xml"); XmlElement emp = doc.CreateElement("Emp"); XmlElement eid = doc.CreateElement("EId"); XmlElement enm = doc.CreateElement("EName"); XmlElement bs = doc.CreateElement("Basic"); eid.InnerText = textBox1.Text; enm.InnerText = textBox2.Text; bs.InnerText = textBox3.Text; emp.AppendChild(eid); emp.AppendChild(enm); emp.AppendChild(bs); emp.SetAttribute("Department", textBox4.Text); emp.SetAttribute("Designation", textBox5.Text); doc.DocumentElement.AppendChild(emp); //Writing to file XmlTextWriter tr = new XmlTextWriter(@"D:\MS.Net\CSharp\XMLParser\XMLParser\Emp.xml", null); tr.Formatting = Formatting.Indented; doc.WriteContentTo(tr); tr.Close();//save the changes }
void PrettyPrintXml(string xml) { var document = new XmlDocument(); try { document.LoadXml(xml); using (var stream = new MemoryStream()) { using (var writer = new XmlTextWriter(stream, Encoding.Unicode)) { writer.Formatting = System.Xml.Formatting.Indented; document.WriteContentTo(writer); writer.Flush(); stream.Flush(); stream.Position = 0; var reader = new StreamReader(stream); xml = reader.ReadToEnd(); } } } catch (XmlException) { } }
public static String FormatXml(String xml) { var mStream = new MemoryStream(); var document = new XmlDocument(); var writer = new XmlTextWriter(mStream, Encoding.Unicode) { Formatting = Formatting.Indented }; try { document.LoadXml(xml); document.WriteContentTo(writer); writer.Flush(); mStream.Flush(); mStream.Position = 0; var sReader = new StreamReader(mStream); return sReader.ReadToEnd(); } catch (XmlException) { return string.Empty; } finally { mStream.Close(); writer.Close(); } }
private static string PrepareComponentUpdateXml(string xmlpath, IDictionary<string, string> paths) { string xml = File.ReadAllText(xmlpath); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable); manager.AddNamespace("avm", "avm"); manager.AddNamespace("cad", "cad"); XPathNavigator navigator = doc.CreateNavigator(); var resourceDependencies = navigator.Select("/avm:Component/avm:ResourceDependency", manager).Cast<XPathNavigator>() .Concat(navigator.Select("/avm:Component/ResourceDependency", manager).Cast<XPathNavigator>()); foreach (XPathNavigator node in resourceDependencies) { string path = node.GetAttribute("Path", "avm"); if (String.IsNullOrWhiteSpace(path)) { path = node.GetAttribute("Path", ""); } string newpath; if (paths.TryGetValue(node.GetAttribute("Name", ""), out newpath)) { node.MoveToAttribute("Path", ""); node.SetValue(newpath); } } StringBuilder sb = new StringBuilder(); XmlTextWriter w = new XmlTextWriter(new StringWriter(sb)); doc.WriteContentTo(w); w.Flush(); return sb.ToString(); }
public static string ConvertToXml(string pXmlString) { string Result = ""; MemoryStream mStream = null; XmlTextWriter writer = null; XmlDocument document = new XmlDocument();; try { document.LoadXml(pXmlString); mStream = new MemoryStream(); writer = new XmlTextWriter(mStream, Encoding.Unicode); writer.Formatting = Formatting.Indented; document.WriteContentTo(writer); writer.Flush(); mStream.Flush(); mStream.Position = 0; StreamReader sReader = new StreamReader(mStream); String FormattedXML = sReader.ReadToEnd(); Result = FormattedXML; } catch { } if (mStream != null) mStream.Close(); if (writer != null) writer.Close(); return Result; }
public static String FormatXml(String value) { using (var mStream = new MemoryStream()) { using (var writer = new XmlTextWriter(mStream, Encoding.Unicode) { Formatting = System.Xml.Formatting.Indented}) { var document = new XmlDocument(); try { document.LoadXml(value); document.WriteContentTo(writer); writer.Flush(); mStream.Flush(); mStream.Position = 0; var sReader = new StreamReader(mStream); return sReader.ReadToEnd(); } catch (XmlException) { } } } return value; }
/// <summary> /// Auto-formats and indents an unformatted XML string. /// </summary> /// <param name="xml"></param> /// <returns></returns> private static string IndentXMLString(string xml) { string outXml = string.Empty; MemoryStream ms = new MemoryStream(); // Create a XMLTextWriter that will send its output to a memory stream (file) XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode); XmlDocument doc = new XmlDocument(); // Load the unformatted XML text string into an instance // of the XML Document Object Model (DOM) doc.LoadXml(xml); // Set the formatting property of the XML Text Writer to indented // the text writer is where the indenting will be performed xtw.Formatting = Formatting.Indented; // write dom xml to the xmltextwriter doc.WriteContentTo(xtw); // Flush the contents of the text writer // to the memory stream, which is simply a memory file xtw.Flush(); // set to start of the memory stream (file) ms.Seek(0, SeekOrigin.Begin); // create a reader to read the contents of // the memory stream (file) StreamReader sr = new StreamReader(ms); // return the formatted string to caller return sr.ReadToEnd(); }
public static String XMLPrint(this String xml){ if (string.IsNullOrEmpty(xml)) return xml; String result = ""; var mStream = new MemoryStream(); var writer = new XmlTextWriter(mStream, Encoding.Unicode); var document = new XmlDocument(); try{ document.LoadXml(xml); writer.Formatting = Formatting.Indented; document.WriteContentTo(writer); writer.Flush(); mStream.Flush(); mStream.Position = 0; var sReader = new StreamReader(mStream); String formattedXML = sReader.ReadToEnd(); result = formattedXML; } catch (XmlException){ } mStream.Close(); writer.Close(); return result; }
public void WritePictureXMLFile() { GlobalDataStore.Logger.Debug("Updating Pictures.xml ..."); List <LabelX.Toolbox.LabelXItem> items = new List <LabelX.Toolbox.LabelXItem>(); DirectoryInfo PicturesRootFolderDirectoryInfo = new DirectoryInfo(PicturesRootFolder); LabelX.Toolbox.Toolbox.GetPicturesFromFolderTree(PicturesRootFolderDirectoryInfo.FullName, ref items); //items = alle ingelezen pictures. Nu gaan wegschrijven. System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement root = doc.CreateElement("LabelXItems"); foreach (LabelX.Toolbox.LabelXItem item in items) { System.Xml.XmlElement itemXML = doc.CreateElement("item"); itemXML.SetAttribute("name", item.Name); itemXML.SetAttribute("hash", item.Hash); root.AppendChild(itemXML); } doc.AppendChild(root); MemoryStream ms = new MemoryStream(); System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8); tw.Formatting = System.Xml.Formatting.Indented; doc.WriteContentTo(tw); doc.Save(PicturesRootFolder + "pictures.xml"); tw.Close(); }
public bool Execute() { if (!File.Exists(WebConfig)) return false; var fileContents = new XmlDocument(); fileContents.Load(WebConfig); var nodes = fileContents.SelectNodes("/configuration/system.serviceModel/client/endpoint"); if (nodes == null || nodes.Count == 0) return false; foreach(var node in nodes) { var address = (node as XmlNode).Attributes["address"].Value; var splitAddress = address.Split('/'); var newAddress = Url + "/" + address[address.Length - 1]; (node as XmlNode).Attributes["address"].Value = newAddress; } using (var writer = XmlWriter.Create(WebConfig)) { fileContents.WriteContentTo(writer); } return true; }
public static string OuterXMLFormatted(this System.Xml.XmlDocument document) { MemoryStream mStream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode); writer.Formatting = System.Xml.Formatting.Indented; // Write the XML into a formatting XmlTextWriter document.WriteContentTo(writer); writer.Flush(); mStream.Flush(); // Have to rewind the MemoryStream in order to read // its contents. mStream.Position = 0; // Read MemoryStream contents into a StreamReader. StreamReader sReader = new StreamReader(mStream); // Extract the text from the StreamReader. string formattedXml = sReader.ReadToEnd(); return(formattedXml); }
public static bool SaveProfile(XmlDocument xml, string path) { XmlTextWriter textWriter = null; FileStream fs = null; try { fs = new FileStream(path, FileMode.OpenOrCreate); textWriter = new XmlTextWriter(fs, Encoding.UTF8); textWriter.Formatting = Formatting.Indented; xml.WriteContentTo(textWriter); } catch (IOException io) { //TODO : Error Log Console.WriteLine(io.StackTrace); return false; } finally { if (textWriter != null) { try { textWriter.Close(); } catch (Exception) { } } } return true; }
private void WriteToStream(XmlDocument document, Stream stream) { XmlTextWriter writer = new XmlTextWriter(stream, Encoding.GetEncoding("ISO-8859-1")); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.IndentChar = ' '; document.WriteContentTo(writer); writer.Close(); }
internal override HttpContent Bindbody(RequestCreContext requestCreContext) { System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); StringBuilder stringBuild = new StringBuilder(); XmlWriter xmlWriter = new XmlTextWriter(new StringWriter(stringBuild)); xmlDocument.WriteContentTo(xmlWriter); StringContent stringContent = new StringContent(stringBuild.ToString()); return(stringContent); }
private static MemoryStream ReformatXmlString(string xmlstream) { MemoryStream stream = new MemoryStream(); XmlTextWriter formatter = new XmlTextWriter(stream, Encoding.UTF8); XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlstream); formatter.Formatting = Formatting.Indented; doc.WriteContentTo(formatter); formatter.Flush(); return stream; }
/** * Turning the DOM4j object in the specified output stream. * * @param xmlContent * The XML document. * @param outStream * The Stream in which the XML document will be written. * @return <b>true</b> if the xml is successfully written in the stream, * else <b>false</b>. */ public static void SaveXmlInStream(XmlDocument xmlContent, Stream outStream) { //XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlContent.NameTable); //nsmgr.AddNamespace("", ""); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.OmitXmlDeclaration = false; XmlWriter writer = XmlTextWriter.Create(outStream,settings); //XmlWriter writer = new XmlTextWriter(outStream,Encoding.UTF8); xmlContent.WriteContentTo(writer); writer.Flush(); }
static void Main(string[] args) { #if DEBUG args = new string[] { "d:\\projects\\csharp\\csquery\\build\\csquery.nuspec", "d:\\projects\\csharp\\csquery\\build\\csquery.test.nuspec", "-version", "1" }; #endif if (args.Length < 4 || args.Length % 2 != 0) { Console.WriteLine("Call with: ProcessNuspec input output [-param value] [-param value] ..."); Console.WriteLine("e.g. ProcessNuspec../source/project.nuspec.template ../source/project.nuspec -version 1.3.3 -id csquery"); } string input = Path.GetFullPath(args[0]); string output = Path.GetFullPath(args[1]); int argPos = 2; var dict = new Dictionary<string, string>(); while (argPos < args.Length) { var argName = args[argPos++]; var argValue = args[argPos++]; if (!argName.StartsWith("-")) { throw new Exception("Every argument must be a -name/value pair."); } dict[argName.Substring(1)]=argValue; } XmlDocument xDoc = new XmlDocument(); xDoc.Load(input); foreach (var item in dict) { var nodes = xDoc.DocumentElement.SelectNodes("//" + item.Key ); if (nodes.Count == 1) { var node = nodes[0]; if (dict.ContainsKey(node.Name) && node.ChildNodes.Count==1) { node.ChildNodes[0].Value = item.Value; } } } //string outputText = "<?xml version=\"1.0\"?>"; XmlWriter writer = XmlWriter.Create(output); xDoc.WriteContentTo(writer); writer.Flush(); writer.Close(); }
private byte[] LoadDocumentIntoMessage(XmlDocument doc) { Stream ms = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(ms, _wcfBinaryDictionary); doc.WriteContentTo(writer); writer.Flush(); byte[] bb = new byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(bb, 0, (int)ms.Length); return bb; }
public string XMLFormat(string xml) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(xml); System.IO.StringWriter sw = new System.IO.StringWriter(); using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw)) { writer.Indentation = 2; // the Indentation writer.Formatting = System.Xml.Formatting.Indented; doc.WriteContentTo(writer); writer.Close(); } return(sw.ToString()); }
public static byte[] ConvertXmlToWcfBinary(XmlDocument document) { byte[] binaryContent = null; using (MemoryStream ms = new MemoryStream()) { XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(ms); document.WriteContentTo(binaryWriter); binaryWriter.Flush(); ms.Position = 0; int length = int.Parse(ms.Length.ToString()); binaryContent = new byte[length]; ms.Read(binaryContent, 0, length); ms.Flush(); } return binaryContent; }
private void AssertXPathNotNull(string xpath) { XmlDocument doc = new XmlDocument(); doc.LoadXml(_stringBuilder.ToString()); XmlNode node = doc.SelectSingleNode(xpath); if (node == null) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.ConformanceLevel = ConformanceLevel.Fragment; XmlWriter writer = XmlWriter.Create(Console.Out, settings); doc.WriteContentTo(writer); writer.Flush(); } Assert.IsNotNull(node, "Not matched: " + xpath); }
public static void AssertXPathNotNull(string documentPath, string xpath) { XmlDocument doc = new XmlDocument(); doc.Load(documentPath); XmlNode node = doc.SelectSingleNode(xpath); if (node == null) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.ConformanceLevel = ConformanceLevel.Fragment; XmlWriter writer = XmlTextWriter.Create(Console.Out, settings); doc.WriteContentTo(writer); writer.Flush(); } Assert.IsNotNull(node); }
/// <summary> /// Writes the single files. /// </summary> /// <param name="document">The document.</param> /// <param name="filename">The filename.</param> private void WriteSingleFiles(System.Xml.XmlDocument document, string filename) { try { //document.Save(filename); XmlTextWriter writer = new XmlTextWriter(filename, System.Text.Encoding.UTF8); writer.Formatting = Formatting.None; document.WriteContentTo(writer); writer.Flush(); writer.Close(); } catch (Exception ex) { throw; } }
/// <summary> /// Pretty Print the input XML string, such as adding indentations to each level of elements /// and carriage return to each line /// </summary> /// <param name="xmlText"></param> /// <returns>New formatted XML string</returns> public static String FormatNicely(String xmlText) { if (xmlText == null || xmlText.Trim().Length == 0) return ""; String result = ""; MemoryStream memStream = new MemoryStream(); XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.Unicode); XmlDocument xmlDoc = new XmlDocument(); try { // Load the XmlDocument with the XML. xmlDoc.LoadXml(xmlText); xmlWriter.Formatting = Formatting.Indented; // Write the XML into a formatting XmlTextWriter xmlDoc.WriteContentTo(xmlWriter); xmlWriter.Flush(); memStream.Flush(); // Have to rewind the MemoryStream in order to read // its contents. memStream.Position = 0; // Read MemoryStream contents into a StreamReader. StreamReader streamReader = new StreamReader(memStream); // Extract the text from the StreamReader. String FormattedXML = streamReader.ReadToEnd(); result = FormattedXML; } catch (Exception) { // Return the original unchanged. result = xmlText; } finally { memStream.Close(); xmlWriter.Close(); } return result; }
private string Pretty(string Message) { System.Xml.XmlDocument Doc = new System.Xml.XmlDocument(); System.IO.MemoryStream MemStr = new System.IO.MemoryStream(); System.Xml.XmlTextWriter XmlWriter = new System.Xml.XmlTextWriter(MemStr, System.Text.Encoding.Unicode); XmlWriter.Formatting = System.Xml.Formatting.Indented; Doc.LoadXml(Message); Doc.WriteContentTo(XmlWriter); XmlWriter.Flush(); MemStr.Flush(); MemStr.Position = 0; string Ret = new System.IO.StreamReader(MemStr).ReadToEnd(); MemStr.Close(); XmlWriter.Close(); return(Ret); }
public void WriteDirectoryXMLFile(string folder, string fnaam) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); GlobalDataStore.Logger.Debug("Updating " + fnaam + " ..."); List <LabelX.Toolbox.LabelXItem> items = new List <LabelX.Toolbox.LabelXItem>(); DirectoryInfo FolderDirectoryInfo = new DirectoryInfo(folder); LabelX.Toolbox.Toolbox.GetFilesFromFolderTree(FolderDirectoryInfo.FullName, ref items); //items = alle ingelezen bestanden. Nu gaan wegschrijven. System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement root = doc.CreateElement("LabelXItems"); foreach (LabelX.Toolbox.LabelXItem item in items) { if (getFileExt(item.Name) == ".xml") { continue; } System.Xml.XmlElement itemXML = doc.CreateElement("item"); itemXML.SetAttribute("name", item.Name); itemXML.SetAttribute("hash", item.Hash); root.AppendChild(itemXML); } doc.AppendChild(root); MemoryStream ms = new MemoryStream(); System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8) { Formatting = System.Xml.Formatting.Indented }; doc.WriteContentTo(tw); doc.Save(folder + fnaam); tw.Close(); sw.Stop(); GlobalDataStore.Logger.Debug("Creating the XML Hash file for the directory took: " + sw.ElapsedMilliseconds + " ms (" + folder + ")"); sw.Reset(); }
protected override void Render(System.Web.UI.HtmlTextWriter writer) { string key = String.Concat("RssFeed", this.PortletID.ToString()); try { if (Common.Cache.IsCached(key) == false) { #if TRACE Context.Trace.Write("RssFeed", String.Concat("Fetching ", XmlDocument)); #endif // Creates a new XmlDocument object XmlDocument rss = new XmlDocument(); // Loads the RSS Feed from the passed URL rss.Load(this.XmlDocument); // create writer System.IO.StringWriter stringWriter = new System.IO.StringWriter(); // writes XML content to writer rss.WriteContentTo(new XmlTextWriter(stringWriter)); // the object cast is needed so the method is not ambiguous Common.Cache.Add(key, (object)stringWriter.ToString(), DateTime.Now.AddDays(1)); } // create XML transformation control System.Web.UI.WebControls.Xml rssfeed = new System.Web.UI.WebControls.Xml(); // sets data for control rssfeed.DocumentContent = (string)Common.Cache[key]; rssfeed.TransformSource = this.XslDocument; // write the HTML output to the writer. rssfeed.RenderControl(writer); } catch (Exception exc) { writer.Write("<center><strong>An error occured in the RSS Feed.</strong></center>"); Trace.Warn("RssFeed", String.Concat("An error occured in ", this.Title, " \n\twith RSS URL ", this.XmlDocument, " \n\twith XSL URL ", this.XslDocument), exc); Common.Cache.Remove(key); } }
/// <summary> Formats a Message object into an HL7 message string using this parser's /// default encoding (XML encoding). This method calls the abstract method /// <code>encodeDocument(...)</code> in order to obtain XML Document object /// representation of the Message, then serializes it to a String. /// </summary> /// <throws> HL7Exception if the data fields in the message do not permit encoding </throws> /// <summary> (e.g. required fields are null) /// </summary> protected internal override System.String doEncode(Message source) { if (source is GenericMessage) { throw new NuGenHL7Exception("Can't XML-encode a GenericMessage. Message must have a recognized structure."); } System.Xml.XmlDocument doc = encodeDocument(source); ((System.Xml.XmlElement)doc.DocumentElement).SetAttribute("xmlns", "urn:hl7-org:v2xml"); System.IO.StringWriter writer = new System.IO.StringWriter(); XmlTextWriter xmlwriter = new XmlTextWriter(writer); doc.WriteContentTo(xmlwriter); string xmlString = writer.ToString(); return(xmlString); }
public static string IdentXML(string xml) { string result = ""; MemoryStream mStream = new MemoryStream(); System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(mStream, Encoding.Unicode); System.Xml.XmlDocument document = new System.Xml.XmlDocument(); try { // Load the XmlDocument with the XML. document.LoadXml(xml); writer.Formatting = System.Xml.Formatting.Indented; // Write the XML into a formatting XmlTextWriter document.WriteContentTo(writer); writer.Flush(); mStream.Flush(); // Have to rewind the MemoryStream in order to read // its contents. mStream.Position = 0; // Read MemoryStream contents into a StreamReader. StreamReader sReader = new StreamReader(mStream); // Extract the text from the StreamReader. string formattedXml = sReader.ReadToEnd(); result = formattedXml; } catch (System.Xml.XmlException) { // Handle the exception } mStream.Close(); writer.Close(); return(result); }
/// <summary> /// Credit from http://stackoverflow.com/questions/1123718/format-xml-string-to-print-friendly-xml-string /// </summary> /// <param name="xml"></param> /// <returns></returns> private static String PrintXml(String xml) { string result; var mStream = new MemoryStream(); var writer = new XmlTextWriter(mStream, Encoding.Unicode); var document = new XmlDocument(); try { // Load the XmlDocument with the XML. document.LoadXml(xml); writer.Formatting = Formatting.Indented; // Write the XML into a formatting XmlTextWriter document.WriteContentTo(writer); writer.Flush(); mStream.Flush(); // Have to rewind the MemoryStream in order to read // its contents. mStream.Position = 0; // Read MemoryStream contents into a StreamReader. var sReader = new StreamReader(mStream); // Extract the text from the StreamReader. var formattedXml = sReader.ReadToEnd(); result = formattedXml; } catch (XmlException xmlException) { return xmlException.Message; } mStream.Close(); writer.Close(); return result; }
public static String PrintXML(String XML) { String Result = ""; MemoryStream mStream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode); XmlDocument document = new XmlDocument(); try { // Load the XmlDocument with the XML. document.LoadXml(XML); writer.Formatting = Formatting.Indented; // Write the XML into a formatting XmlTextWriter document.WriteContentTo(writer); writer.Flush(); mStream.Flush(); // Have to rewind the MemoryStream in order to read // its contents. mStream.Position = 0; // Read MemoryStream contents into a StreamReader. StreamReader sReader = new StreamReader(mStream); // Extract the text from the StreamReader. String FormattedXML = sReader.ReadToEnd(); Result = FormattedXML; } catch (XmlException) { } mStream.Close(); writer.Close(); return Result; }
private static void AssertXPathMatchesExactlyOneInner(XmlDocument doc, string xpath) { XmlNodeList nodes = doc.SelectNodes(xpath); if (nodes == null || nodes.Count != 1) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.ConformanceLevel = ConformanceLevel.Fragment; XmlWriter writer = XmlTextWriter.Create(Console.Out, settings); doc.WriteContentTo(writer); writer.Flush(); if (nodes != null && nodes.Count > 1) { Assert.Fail("Too Many matches for XPath: {0}", xpath); } else { Assert.Fail("No Match: XPath failed: {0}", xpath); } } }
static void Main(string[] args) { initialize(args); try { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; XmlDocument doc = new XmlDocument(); doc.Load(textReader); XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting = Formatting.Indented; writer.Indentation = 4; doc.WriteContentTo(writer); } catch (Exception e) { Console.WriteLine("Exception : " + e); } }
public static void ExportMessages() { HelpDAO dao = new HelpDAO(); List<HelpMessageBean> messages = dao.getHelpMessages(); XmlDocument document = new XmlDocument(); XmlElement root = document.CreateElement("messages"); document.AppendChild(root); foreach (HelpMessageBean messageBean in messages) { XmlElement message = document.CreateElement("message"); message.SetAttribute( "key", messageBean.messageKey ); XmlText txt = document.CreateTextNode( messageBean.message ); message.AppendChild( txt ); root.AppendChild( message ); } StringWriter sw = new StringWriter(); XmlWriter writer = new UTRSXmlWriter( sw ); document.WriteContentTo( writer ); if( FileManager.WriteFile( Encoding.UTF8.GetBytes( sw.ToString() ), "help-messages.xml" ) ) LogManager.Info( "Help Messages have been successfully exported." ); }
private static string IndentXMLString(string xml) { string outXml = string.Empty; System.IO.MemoryStream ms = new System.IO.MemoryStream(); // Create a XMLTextWriter that will send its output to a memory stream (file) System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, System.Text.Encoding.Unicode); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); try { // Load the unformatted XML text string into an instance // of the XML Document Object Model (DOM) doc.LoadXml(xml); // Set the formatting property of the XML Text Writer to indented // the text writer is where the indenting will be performed xtw.Formatting = System.Xml.Formatting.Indented; xtw.Indentation = 4; // write dom xml to the xmltextwriter doc.WriteContentTo(xtw); // Flush the contents of the text writer // to the memory stream, which is simply a memory file xtw.Flush(); // set to start of the memory stream (file) ms.Seek(0, System.IO.SeekOrigin.Begin); // create a reader to read the contents of // the memory stream (file) System.IO.StreamReader sr = new System.IO.StreamReader(ms); // return the formatted string to caller return(sr.ReadToEnd()); } catch (Exception ex) { return(ex.ToString()); } }
public static void AssertXPathIsNull(string xml, string xpath, Dictionary<string, string> namespaces) { var doc = new XmlDocument(); doc.LoadXml(xml); var namespaceManager = new XmlNamespaceManager(doc.NameTable); foreach (var namespaceKvp in namespaces) namespaceManager.AddNamespace(namespaceKvp.Key, namespaceKvp.Value); var node = doc.SelectSingleNode(xpath, namespaceManager); if (node != null) { var settings = new XmlWriterSettings { Indent = true, ConformanceLevel = ConformanceLevel.Fragment }; var writer = XmlTextWriter.Create(Console.Out, settings); doc.WriteContentTo(writer); writer.Flush(); } Assert.IsNull(node); }
public static string SerializeProject(IList assemblies, string configFileName) { XmlDocument xmlDoc = new XmlDocument(); XmlNode rootNode = xmlDoc.CreateElement("project"); xmlDoc.AppendChild(rootNode); SerializeConfig(configFileName, xmlDoc, rootNode); foreach (Assembly asm in assemblies) SerializeAssembly(asm, xmlDoc, rootNode); StringBuilder stringBuilder = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, settings)) { xmlDoc.WriteContentTo(xmlWriter); xmlWriter.Flush(); return stringBuilder.ToString(); } }
internal static string IndentXml(string unformatedXml) { MemoryStream ms = new MemoryStream(); XmlTextWriter xtw = new XmlTextWriter(ms, System.Text.Encoding.Unicode); XmlDocument doc = new XmlDocument(); try { doc.LoadXml(unformatedXml); xtw.Formatting = Formatting.Indented; doc.WriteContentTo(xtw); xtw.Flush(); ms.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(ms); return sr.ReadToEnd(); } catch { return "Error while formatting Xml..."; } }
public static string SerializeConfiguration(PresentationModel model) { XmlDocument xmlDoc = new XmlDocument(); XmlNode rootNode = xmlDoc.CreateElement("naspect"); xmlDoc.AppendChild(rootNode); XmlNode configNode = xmlDoc.CreateElement("configuration"); rootNode.AppendChild(configNode); foreach (PresentationAspect aspect in model.Aspects) SerializeAspect(aspect, xmlDoc, configNode); StringBuilder stringBuilder = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, settings)) { xmlDoc.WriteContentTo(xmlWriter); xmlWriter.Flush(); return stringBuilder.ToString() ; } }
private void button2_Click(object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); doc.Load(@"D:\nt-pritz\MS.NET\MS FRAMEWORK\CLASS DEMO\WindowsFormsApplication2\WindowsFormsApplication2\XMLFile1.xml"); XmlElement emp = doc.CreateElement("emp"); XmlElement id = doc.CreateElement("id"); XmlElement name = doc.CreateElement("name"); XmlElement basic = doc.CreateElement("basic"); id.InnerText = textBox1.Text; name.InnerText = textBox2.Text; basic.InnerText = textBox3.Text; emp.AppendChild(id); emp.AppendChild(name); emp.AppendChild(basic); emp.SetAttribute("designation",textBox4.Text); doc.DocumentElement.AppendChild(emp); XmlTextWriter tr = new XmlTextWriter(@"D:\nt-pritz\MS.NET\MS FRAMEWORK\CLASS DEMO\WindowsFormsApplication2\WindowsFormsApplication2\XMLFile1.xml",null); tr.Formatting=Formatting.Indented; doc.WriteContentTo(tr); tr.Close(); }