//ArrayList openElements = new ArrayList(); public void SerializeXml(IList<StarSystem> starSystems) { MemoryStream memXmlStream = new MemoryStream(); XmlSerializer serializer = new XmlSerializer(starSystems.GetType(), null, new Type[] { typeof(Planet), typeof(StarSystem) }, new XmlRootAttribute("Stars"), null, null); serializer.Serialize(memXmlStream, starSystems); XmlDocument xmlDoc = new XmlDocument(); memXmlStream.Seek(0, SeekOrigin.Begin); xmlDoc.Load(memXmlStream); XmlProcessingInstruction newPI; String PItext = string.Format("type='text/xsl' href='{0}'", "system.xslt"); newPI = xmlDoc.CreateProcessingInstruction("xml-stylesheet", PItext); xmlDoc.InsertAfter(newPI, xmlDoc.FirstChild); // Now write the document // out to the final output stream XmlTextWriter wr = new XmlTextWriter("system.xml", System.Text.Encoding.ASCII); wr.Formatting = Formatting.Indented; wr.IndentChar = '\t'; wr.Indentation = 1; XmlWriterSettings settings = new XmlWriterSettings(); XmlWriter writer = XmlWriter.Create(wr, settings); xmlDoc.WriteTo(writer); writer.Flush(); //Console.Write(xmlDoc.InnerXml); }
/// <summary> /// Define o valor de uma configuração /// </summary> /// <param name="file">Caminho do arquivo (ex: c:\program.exe.config)</param> /// <param name="key">Nome da configuração</param> /// <param name="value">Valor a ser salvo</param> /// <returns></returns> public static bool SetValue(string file, string key, string value) { var fileDocument = new XmlDocument(); fileDocument.Load(file); var nodes = fileDocument.GetElementsByTagName(AddElementName); if (nodes.Count == 0) { return false; } for (var i = 0; i < nodes.Count; i++) { var node = nodes.Item(i); if (node == null || node.Attributes == null || node.Attributes.GetNamedItem(KeyPropertyName) == null) continue; if (node.Attributes.GetNamedItem(KeyPropertyName).Value == key) { node.Attributes.GetNamedItem(ValuePropertyName).Value = value; } } var writer = new XmlTextWriter(file, null) { Formatting = Formatting.Indented }; fileDocument.WriteTo(writer); writer.Flush(); writer.Close(); return true; }
public static int Main (string [] args) { if (args.Length == 0) return 1; AbiMode = false; AssemblyCollection acoll = new AssemblyCollection (); foreach (string arg in args) { if (arg == "--abi") AbiMode = true; else acoll.Add (arg); } XmlDocument doc = new XmlDocument (); acoll.Document = doc; acoll.DoOutput (); var writer = new WellFormedXmlWriter (new XmlTextWriter (Console.Out) { Formatting = Formatting.Indented }); XmlNode decl = doc.CreateXmlDeclaration ("1.0", "utf-8", null); doc.InsertBefore (decl, doc.DocumentElement); doc.WriteTo (writer); return 0; }
private static void UpdateProjectFile(ParsedArgs pa) { //load the project file var template = new System.Xml.XmlDocument(); template.Load(pa.TemplateFile); //update it RemoveTargets(template); AddTargets(template, pa.TargetsDirectory); UpdateReferencePaths(template); //write it back to disk var output = new System.Xml.XmlDocument(); foreach (var node in template.ChildNodes.Cast <XmlNode>().Where(w => w.NodeType != XmlNodeType.XmlDeclaration)) { var importNode = output.ImportNode(node, true); output.AppendChild(importNode); } using (var xWriter = XmlWriter.Create(pa.TemplateFile, new XmlWriterSettings() { Indent = true, IndentChars = " " })) { output.WriteTo(xWriter); } }
/// <summary> /// Transform: read from an input stream and write to an output stream. /// </summary> public void Transform(Stream inputStream, Stream outputStream) { var document = new XmlDocument(); document.PreserveWhitespace = true; document.Load(inputStream); foreach (XmlNode node in document.SelectNodes("/root/data/value")) { var child = node.FirstChild; if (child != null && child.NodeType == XmlNodeType.Text) { var original = child.Value; var args = new TransformStringEventArgs { Value = original }; OnTransformString(args); if (args.Value != original) { child.Value = args.Value; } } } using (var xmlWriter = XmlWriter.Create(outputStream)) { document.WriteTo(xmlWriter); } }
private string GetXmlDocumentAsString(XmlDocument xml) { var xmlString = string.Empty; using (var stream = new MemoryStream()) { using (var streamWriter = new StreamWriter(stream)) { var xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Encoding = Encoding.UTF8; xmlWriterSettings.Indent = true; using (var xmlWriter = XmlWriter.Create(streamWriter, xmlWriterSettings)) { xml.WriteTo(xmlWriter); xmlWriter.Flush(); xmlWriter.Close(); } using (var streamReader = new StreamReader(stream)) { stream.Position = 0; xmlString = streamReader.ReadToEnd(); streamReader.Close(); } } } return xmlString; }
/// <summary> /// Converts a XmlDocument to string /// </summary> /// <param name="doc">XmlDocument to be converted</param> /// <returns>string with the xml content</returns> public static string Write(XmlDocument doc) { StringWriter sw = new StringWriter(); XmlWriter xw = new XmlTextWriter(sw); doc.WriteTo(xw); return sw.ToString(); }
public ActionResult Create(string webConfigXml, string transformXml) { try { var transformation = new XmlTransformation(transformXml, false, null); var document = new XmlDocument(); document.LoadXml(webConfigXml); var success = transformation.Apply(document); if (success) { var stringBuilder = new StringBuilder(); var xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.IndentChars = " "; using (var xmlTextWriter = XmlTextWriter.Create(stringBuilder, xmlWriterSettings)) { document.WriteTo(xmlTextWriter); } return Content(stringBuilder.ToString(), "text/xml"); } else { return ErrorXml("Transformation failed for unkown reason"); } } catch (XmlTransformationException xmlTransformationException) { return ErrorXml(xmlTransformationException.Message); } catch (XmlException xmlException) { return ErrorXml(xmlException.Message); } }
public string CreateXml(XmlDocument doc, string cookie, int page, int count) { if (doc.DocumentElement == null) throw new ArgumentNullException("DocumentElement"); XmlAttributeCollection attrs = doc.DocumentElement.Attributes; if (cookie != null) { XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie"); pagingAttr.Value = cookie; attrs.Append(pagingAttr); } XmlAttribute pageAttr = doc.CreateAttribute("page"); pageAttr.Value = System.Convert.ToString(page); attrs.Append(pageAttr); XmlAttribute countAttr = doc.CreateAttribute("count"); countAttr.Value = System.Convert.ToString(count); attrs.Append(countAttr); StringBuilder sb = new StringBuilder(1024); StringWriter stringWriter = new StringWriter(sb); XmlTextWriter writer = new XmlTextWriter(stringWriter); doc.WriteTo(writer); writer.Close(); return sb.ToString(); }
/// <summary> /// Converts the given XML string into a more readable format. /// </summary> internal static string PrettyPrintXml(string xml) { XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.ConformanceLevel = ConformanceLevel.Fragment; settings.NewLineHandling = NewLineHandling.Replace; settings.NewLineChars = "\r\n"; settings.Indent = true; settings.IndentChars = "\t"; settings.NewLineOnAttributes = true; XmlDocument doc = new XmlDocument(); try { doc.LoadXml(xml); } catch (Exception e) { throw new Exception("Invalid XML: " + xml, e); } var sb = new StringBuilder(); using (var writer = XmlTextWriter.Create(sb, settings)) doc.WriteTo(writer); return sb.ToString(); }
protected override string GetInnerResponse() { XmlDocument doc = new XmlDocument(); XmlElement musicFoldersElem = doc.CreateElement("musicFolders"); List<string> musicFolders = this.GetExampleFolderNames(); for (int i=1;i<=musicFolders.Count;i++) { XmlElement folder = doc.CreateElement("musicFolder"); XmlAttribute idAttr = doc.CreateAttribute("id"); XmlAttribute nameAttr = doc.CreateAttribute("name"); idAttr.Value = i.ToString(); nameAttr.Value = musicFolders[i-1]; folder.Attributes.Append(idAttr); folder.Attributes.Append(nameAttr); musicFoldersElem.AppendChild(folder); } doc.AppendChild(musicFoldersElem); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); doc.WriteTo(xtw); return sw.ToString(); }
public static string PrettyPrint(XmlDocument xml) { var result = ""; if (xml == null) return result; using (var ms = new MemoryStream()) { var writer = new XmlTextWriter(ms, Encoding.Unicode); writer.Formatting = Formatting.Indented; xml.WriteTo(writer); writer.Flush(); ms.Flush(); ms.Position = 0; var reader = new StreamReader(ms); result = reader.ReadToEnd(); writer.Close(); reader.Close(); } return result; }
public override void Save(object value, string sectionName, string fileName) { XmlNode xmlNode = this.Serialize(value); XmlDocument document = new XmlDocument(); document.AppendChild(document.ImportNode(xmlNode,true)); // Encrypt xml EncryptXml enc = new EncryptXml(document); enc.AddKeyNameMapping("db", ReadServerEncryptionKey()); XmlNodeList list = document.SelectNodes("//Password"); foreach ( XmlNode n in list ) { XmlElement el = (XmlElement)n; EncryptedData data = enc.Encrypt(el, "db"); enc.ReplaceElement(el, data); } XmlTextWriter writer = new XmlTextWriter(fileName, null); writer.Formatting = Formatting.Indented; document.WriteTo(writer); writer.Flush(); writer.Close(); }
private void Init(string url) { XmlDocument xml = new XmlDocument(); xml.Load(url); StringWriter xmlString = new StringWriter(); xml.WriteTo(new XmlTextWriter(xmlString)); m_DeviceXml = xmlString.ToString(); // Set up namespace manager for XPath XmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable); ns.AddNamespace("n",xml.ChildNodes[1].NamespaceURI); m_BaseUrl = xml.SelectSingleNode("n:root/n:URLBase",ns).InnerText; m_DeviceType = xml.SelectSingleNode("n:root/n:device/n:deviceType",ns).InnerText; m_FriendlyName = xml.SelectSingleNode("n:root/n:device/n:friendlyName",ns).InnerText; m_Manufacturer = xml.SelectSingleNode("n:root/n:device/n:manufacturer",ns).InnerText; m_ManufacturerUrl = xml.SelectSingleNode("n:root/n:device/n:manufacturerURL",ns).InnerText; m_ModelDescription = xml.SelectSingleNode("n:root/n:device/n:modelDescription",ns).InnerText; m_ModelName = xml.SelectSingleNode("n:root/n:device/n:modelName",ns).InnerText; m_ModelNumber = xml.SelectSingleNode("n:root/n:device/n:modelNumber",ns).InnerText; m_ModelUrl = xml.SelectSingleNode("n:root/n:device/n:modelURL",ns).InnerText; m_SerialNumber = xml.SelectSingleNode("n:root/n:device/n:serialNumber",ns).InnerText; m_UDN = xml.SelectSingleNode("n:root/n:device/n:UDN",ns).InnerText; m_PresentationUrl = xml.SelectSingleNode("n:root/n:device/n:presentationURL",ns).InnerText; }
public override void SignFile(String xmlFilePath, object xmlDigitalSignature) { XmlElement XmlDigitalSignature = (XmlElement)xmlDigitalSignature; XmlDocument Document = new XmlDocument(); Document.PreserveWhitespace = true; XmlTextReader XmlFile = new XmlTextReader(xmlFilePath); Document.Load(XmlFile); XmlFile.Close(); // Append the element to the XML document. Document.DocumentElement.AppendChild(Document.ImportNode(XmlDigitalSignature, true)); if (Document.FirstChild is XmlDeclaration) { Document.RemoveChild(Document.FirstChild); } // Save the signed XML document to a file specified // using the passed string. using (XmlTextWriter textwriter = new XmlTextWriter(xmlFilePath, new UTF8Encoding(false))) { textwriter.WriteStartDocument(); Document.WriteTo(textwriter); textwriter.Close(); } }
/// <summary> /// Converts entries in a XML document. /// </summary> /// <param name="entries">The entries.</param> /// <returns>The XML document that represents the entries.</returns> public string Convert(IEnumerable<string> entries) { var doc = new XmlDocument(); var xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null); var root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); var rootElement = doc.CreateElement("directory"); foreach (var entry in entries) { var element = doc.CreateElement("entry"); var textNode = doc.CreateTextNode(entry); element.AppendChild(textNode); rootElement.AppendChild(element); } doc.AppendChild(rootElement); using (var stringWriter = new StringWriter(CultureInfo.InvariantCulture)) using (var xmlTextWriter = XmlWriter.Create(stringWriter)) { doc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); return stringWriter.GetStringBuilder().ToString(); } }
/// <summary> /// Creates the FetchXML Query. /// </summary> /// <param name="xml">The FetchXMLQuery.</param> /// <param name="cookie">The paging cookie.</param> /// <param name="page">The page number.</param> /// <param name="count">The records per page count.</param> /// <returns>Formatted FechXML Query</returns> protected string CreateXml(string xml, string cookie, int page, int count) { StringReader stringReader = new StringReader(xml); XmlTextReader reader = new XmlTextReader(stringReader); // Load document XmlDocument doc = new XmlDocument(); doc.Load(reader); XmlAttributeCollection attrs = doc.DocumentElement.Attributes; if (cookie != null) { XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie"); pagingAttr.Value = cookie; attrs.Append(pagingAttr); } XmlAttribute pageAttr = doc.CreateAttribute("page"); pageAttr.Value = System.Convert.ToString(page); attrs.Append(pageAttr); XmlAttribute countAttr = doc.CreateAttribute("count"); countAttr.Value = System.Convert.ToString(count); attrs.Append(countAttr); StringBuilder sb = new StringBuilder(1024); StringWriter stringWriter = new StringWriter(sb); XmlTextWriter writer = new XmlTextWriter(stringWriter); doc.WriteTo(writer); writer.Close(); return sb.ToString(); }
private void IntroduceErrorToMessage(ref Message message) { XmlDocument doc = new XmlDocument(); doc.Load(message.GetReaderAtBodyContents()); XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace("tempuri", "http://tempuri.org/"); XmlElement xNode = doc.SelectSingleNode("//tempuri:x", nsManager) as XmlElement; XmlText xValue = xNode.FirstChild as XmlText; xValue.Value = (double.Parse(xValue.Value, CultureInfo.InvariantCulture) + 1).ToString(CultureInfo.InvariantCulture); MemoryStream ms = new MemoryStream(); XmlWriterSettings writerSettings = new XmlWriterSettings { CloseOutput = false, OmitXmlDeclaration = true, Encoding = Encoding.UTF8, }; XmlWriter writer = XmlWriter.Create(ms, writerSettings); doc.WriteTo(writer); writer.Close(); ms.Position = 0; XmlReader reader = XmlReader.Create(ms); Message newMessage = Message.CreateMessage(message.Version, null, reader); newMessage.Headers.CopyHeadersFrom(message); newMessage.Properties.CopyProperties(message.Properties); message.Close(); message = newMessage; }
// This function generates the XML request body // for the FolderSync request. protected override void GenerateXMLPayload() { // If WBXML was explicitly set, use that if (WbxmlBytes != null) return; // Otherwise, use the properties to build the XML and then WBXML encode it XmlDocument folderSyncXML = new XmlDocument(); XmlDeclaration xmlDeclaration = folderSyncXML.CreateXmlDeclaration("1.0", "utf-8", null); folderSyncXML.InsertBefore(xmlDeclaration, null); XmlNode folderSyncNode = folderSyncXML.CreateElement(Xmlns.folderHierarchyXmlns, "FolderSync", Namespaces.folderHierarchyNamespace); folderSyncNode.Prefix = Xmlns.folderHierarchyXmlns; folderSyncXML.AppendChild(folderSyncNode); if (syncKey == "") syncKey = "0"; XmlNode syncKeyNode = folderSyncXML.CreateElement(Xmlns.folderHierarchyXmlns, "SyncKey", Namespaces.folderHierarchyNamespace); syncKeyNode.Prefix = Xmlns.folderHierarchyXmlns; syncKeyNode.InnerText = syncKey; folderSyncNode.AppendChild(syncKeyNode); StringWriter sw = new StringWriter(); XmlTextWriter xmlw = new XmlTextWriter(sw); xmlw.Formatting = Formatting.Indented; folderSyncXML.WriteTo(xmlw); xmlw.Flush(); XmlString = sw.ToString(); }
// Accumulation format is now called Victory. private static void Upgrades0210() { var xml = new XmlDocument(); if (Config.Settings.SeparateEventFiles) { var targetPath = Path.Combine(Program.BasePath, "Tournaments"); if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath); var files = new List<string>(Directory.GetFiles(targetPath, "*.tournament.dat", SearchOption.TopDirectoryOnly)); files.AddRange(Directory.GetFiles(targetPath, "*.league.dat", SearchOption.TopDirectoryOnly)); foreach (string filename in files) { xml.Load(filename); var oldNodes = xml.SelectNodes("//Events/Tournaments/Tournament/Format[. = 'Accumulation']"); if (oldNodes != null) foreach (XmlNode oldNode in oldNodes) oldNode.InnerText = "Victory"; oldNodes = xml.SelectNodes("//Events/Leagues/League/Format[. = 'Accumulation']"); if (oldNodes != null) foreach (XmlNode oldNode in oldNodes) oldNode.InnerText = "Victory"; var writer = new XmlTextWriter(new FileStream(filename, FileMode.Create), null) { Formatting = Formatting.Indented, Indentation = 1, IndentChar = '\t' }; xml.WriteTo(writer); writer.Flush(); writer.Close(); } } else if (File.Exists(Path.Combine(Program.BasePath, "Events.dat"))) { xml.Load(Path.Combine(Program.BasePath, "Events.dat")); var oldNodes = xml.SelectNodes("//Events/Tournaments/Tournament/Format[. = 'Accumulation']"); if (oldNodes != null) foreach (XmlNode oldNode in oldNodes) oldNode.InnerText = "Victory"; oldNodes = xml.SelectNodes("//Events/Leagues/League/Format[. = 'Accumulation']"); if (oldNodes != null) foreach (XmlNode oldNode in oldNodes) oldNode.InnerText = "Victory"; var writer = new XmlTextWriter(new FileStream(Path.Combine(Program.BasePath, "Events.dat"), FileMode.Create), null) { Formatting = Formatting.Indented, Indentation = 1, IndentChar = '\t' }; xml.WriteTo(writer); writer.Flush(); writer.Close(); } }
public static void Read() { XmlDocument xmlDocument = new XmlDocument(); XmlElement rootElement = xmlDocument.CreateElement("sales"); IEnumerable<SalesReportByVendor> sales; string nativeSQLQuery = "SELECT v.VendorName, s.Date, SUM(s.Sum) as [Sum] " + "FROM Sales AS s INNER JOIN Products AS p ON s.ProductID = p.ID " + "INNER JOIN Vendors AS v ON p.VendorID = v.ID " + "GROUP BY v.VendorName, s.Date"; sales = db.Database.SqlQuery<SalesReportByVendor>(nativeSQLQuery); foreach (SalesReportByVendor sale in sales) { XmlElement saleElement = xmlDocument.CreateElement("sale"); saleElement.SetAttribute("vendor", sale.VendorName); XmlElement summaryElement = xmlDocument.CreateElement("summary"); summaryElement.SetAttribute("date", sale.Date.ToString("dd-MMM-yyyy", CultureInfo.GetCultureInfo("en-US"))); summaryElement.SetAttribute("total-sum", sale.Sum.ToString("0.00", CultureInfo.GetCultureInfo("en-US"))); saleElement.AppendChild(summaryElement); rootElement.AppendChild(saleElement); } xmlDocument.AppendChild(rootElement); XmlWriter xmlReportFile = GenerateXMLFile(XMLReportFileName); xmlReportFile.WriteStartDocument(); using (xmlReportFile) { xmlDocument.WriteTo(xmlReportFile); } Console.WriteLine(xmlDocument.DocumentElement.OuterXml); }
static int Main(string[] args) { if (args.Length < 1) return ExitErr("args.Length < 1"); if(!File.Exists(args[0])) return ExitErr("File '" + args[0] + "' not Exists"); XmlDocument xDoc = new XmlDocument(); try { xDoc.Load(args[0]); } catch(Exception ex) { return ExitErr(ex.ToString()); } foreach (XmlNode chNode in xDoc.ChildNodes) SortAttribs(chNode); foreach (XmlNode chNode in xDoc.ChildNodes) SortChildNodes(chNode); StringBuilder sb = new StringBuilder(); using (var xw = XmlWriter.Create(sb, new XmlWriterSettings { //Encoding = Encoding.UTF8, Indent = true, })) xDoc.WriteTo(xw); Console.Out.Write(sb.ToString()); return 0; }
static void Main(string[] args) { XmlDocument doc = new XmlDocument(); XmlNode booksnode = doc.AppendChild(doc.CreateElement("Books")); XmlNode booknode = booksnode.AppendChild(doc.CreateElement("Book")); //booksnode.RemoveChild(booknode); XmlAttribute bookname = booknode.Attributes.Append(doc.CreateAttribute("Name")); bookname.Value = "test"; XmlWriter writer = XmlWriter.Create("booklist.xml"); doc.WriteTo(writer); writer.Close(); XslCompiledTransform transform = new XslCompiledTransform(true); transform.Load("template.xsl"); transform.Transform("testdata.xml", "testdata.html"); string[] data = { "a", "b", "c" }; List<string> strings = new List<string>(data); string temp = string.Empty; foreach (string s in strings) { temp += s; } MessageBox.Show(temp); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }
public static void CreateKmlFile(string fileName, IEnumerable<Location> locations) { try { var doc = new XmlDocument(); var xdoc = new XDocument( new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty), new XElement(Kmlns + "kml", new XElement(Kmlns + "Document", new XElement(Kmlns + "name", "None"), new XElement(Kmlns + "Style", new XAttribute("id", "defaultStyle"), new XElement(Kmlns + "LineStyle", new XElement(Kmlns + "color", "ffffffff"), new XElement(Kmlns + "colorMode", "normal"), new XElement(Kmlns + "width", 1)), new XElement(Kmlns + "PolyStyle", new XElement(Kmlns + "color", "880000ff"), new XElement(Kmlns + "colorMode", "normal"), new XElement(Kmlns + "fill", 1), new XElement(Kmlns + "outline", 1))), BuildGeographicPolylineType("FoV", locations)))); doc.LoadXml(xdoc.Root.ToString()); using (var writer = XmlWriter.Create(fileName)) { doc.WriteTo(writer); } } catch (Exception) { Console.WriteLine("Could not create KML file!!!!"); } }
public static void WriteGzip(XmlDocument theDoc, Stream theStream) { MemoryStream ms = new MemoryStream(); XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.Encoding = Encoding.UTF8; xmlSettings.ConformanceLevel = ConformanceLevel.Document; xmlSettings.Indent = false; xmlSettings.NewLineOnAttributes = false; xmlSettings.CheckCharacters = true; xmlSettings.IndentChars = ""; XmlWriter tw = XmlWriter.Create(ms, xmlSettings); theDoc.WriteTo(tw); tw.Flush(); tw.Close(); byte[] buffer = ms.GetBuffer(); GZipStream compressedzipStream = new GZipStream(theStream, CompressionMode.Compress, true); compressedzipStream.Write(buffer, 0, buffer.Length); // Close the stream. compressedzipStream.Flush(); compressedzipStream.Close(); // Force a flush theStream.Flush(); }
public bool Write(Database database, StreamWriter stream, bool encrypt = true) { // Clear the last error this.ErrorString = string.Empty; XmlDocument document = new XmlDocument(); this.Append(document, document, database); StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(sw); xw.Formatting = Formatting.Indented; xw.Indentation = 4; document.WriteTo(xw); string fileDataString = sw.ToString(); if (encrypt) { DatabaseCrypto.CryptoStatus status; fileDataString = DatabaseCrypto.Encrypt(fileDataString, database.Password, database.Compression, out status); if (status != DatabaseCrypto.CryptoStatus.NoError) { this.ErrorString = DatabaseCrypto.StatusMessage(status); return false; } } stream.Write(fileDataString); return true; }
private string FixResource(string path) { XmlDocument doc = new XmlDocument(); doc.Load(path); Regex rxName = new Regex(@".*\.(.*)\.DisplayName$"); foreach (XmlNode node in doc.SelectNodes("//root/data/value")) { if (String.IsNullOrEmpty(node.InnerText) || node.InnerText == "Sage.Platform.Orm.Entities.OrmFieldProperty") { String name = ((XmlElement)node.ParentNode).GetAttribute("name"); Match m = rxName.Match(name); if (m.Success) { node.InnerText = m.Groups[1].Value; } } } using (StringWriter buf = new StringWriter()) { XmlWriterSettings settings = new XmlWriterSettings { Indent = true }; using (XmlWriter w = XmlWriter.Create(buf, settings)) { doc.WriteTo(w); } return buf.GetStringBuilder().ToString(); } }
public int Generate(XmlDocument sourceDocument, Stream output) { var source = new CircularStream(); XmlWriter w = new XmlTextWriter(source, Encoding.Default); sourceDocument.WriteTo(w); return Generate(source, output); }
private void SavePrefs() { XmlTextWriter writer = new XmlTextWriter(location, System.Text.Encoding.UTF8); writer.Formatting = Formatting.Indented; document.WriteTo(writer); writer.Flush(); writer.Close(); }
private static string ConvertXmlDocumentToString(XmlDocument xmlDocument) { StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);; xmlDocument.WriteTo(xmlTextWriter); return stringWriter.ToString(); }
public static String xmlToString(XmlDocument xml) { StringWriter sw = new StringWriter(); XmlTextWriter tx = new XmlTextWriter(sw); xml.WriteTo(tx); string str = sw.ToString(); return str; }
/// <summary> /// Convert a XmlDocument To String /// </summary> /// <param name="xDoc"></param> /// <returns></returns> public static string XmlToString(XmlDocument xDoc) { using (StringWriter sw = new StringWriter()) { XmlTextWriter tx = new XmlTextWriter(sw); xDoc.WriteTo(tx); return sw.ToString(); } }
private string OutputResource(FhirXmlSerializer serializer, Resource item) { string newJson = serializer.SerializeToString(item); var doc = new System.Xml.XmlDocument(); doc.LoadXml(newJson); var sr = new System.IO.StringWriter(); var xw = new XmlTextWriter(sr); xw.Formatting = Formatting.Indented; xw.IndentChar = '\t'; xw.Indentation = 1; doc.WriteTo(xw); return(sr.ToString()); }
public string createXMLFromCustomList(List <List <KeyValuePair <string, string> > > myList, int AddressListId) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); //create nodes System.Xml.XmlElement root = doc.CreateElement("addressList"); System.Xml.XmlElement addressListName = doc.CreateElement("addressListName"); _addressListName = Guid.NewGuid().ToString("N"); addressListName.InnerXml = _addressListName; root.AppendChild(addressListName); System.Xml.XmlElement addressMappingId = doc.CreateElement("addressMappingId"); addressMappingId.InnerXml = AddressListId.ToString(); root.AppendChild(addressMappingId); System.Xml.XmlElement addresses = doc.CreateElement("addresses"); root.AppendChild(addresses); System.Xml.XmlElement address = null; foreach (List <KeyValuePair <string, string> > a in myList) { foreach (KeyValuePair <string, string> aa in a) { address = doc.CreateElement("address"); System.Xml.XmlElement i = doc.CreateElement(aa.Key); i.InnerXml = aa.Value; address.AppendChild(i); } addresses.AppendChild(address); } doc.AppendChild(root); string xmlString = null; using (StringWriter stringWriter = new StringWriter()) { using (XmlWriter xmlTextWriter = XmlWriter.Create(stringWriter)) { doc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); xmlString = stringWriter.GetStringBuilder().ToString(); } } return(xmlString); }
/// <summary> /// Get the XML string version of the currently loaded wiring documents. /// </summary> /// <returns>The XML string version of the currently loaded wiring documents.</returns> public string ConvertToXMLString() { System.Xml.XmlDocument doc = this.SaveDocument(); using (var stringWriter = new System.IO.StringWriter()) { System.Xml.XmlWriterSettings xmlWriteSettings = new System.Xml.XmlWriterSettings(); xmlWriteSettings.OmitXmlDeclaration = true; xmlWriteSettings.Indent = true; xmlWriteSettings.NewLineOnAttributes = false; using (var xmlTextWriter = System.Xml.XmlWriter.Create(stringWriter, xmlWriteSettings)) { doc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); string stringval = stringWriter.GetStringBuilder().ToString(); return(stringval); } } }
public string createXMLFromAddressList() { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); //create nodes System.Xml.XmlElement root = doc.CreateElement("addressList"); System.Xml.XmlElement addressListName = doc.CreateElement("addressListName"); _addressListName = Guid.NewGuid().ToString("N"); addressListName.InnerXml = _addressListName; root.AppendChild(addressListName); System.Xml.XmlElement addressMappingId = doc.CreateElement("addressMappingId"); addressMappingId.InnerXml = "2"; root.AppendChild(addressMappingId); System.Xml.XmlElement addresses = doc.CreateElement("addresses"); root.AppendChild(addresses); foreach (addressItem a in addressList) { System.Xml.XmlElement address = doc.CreateElement("address"); System.Xml.XmlElement fname = doc.CreateElement("First_name"); fname.InnerXml = a._First_name; address.AppendChild(fname); System.Xml.XmlElement lname = doc.CreateElement("Last_name"); lname.InnerXml = a._Last_name; address.AppendChild(lname); System.Xml.XmlElement Organization = doc.CreateElement("Organization"); Organization.InnerXml = a._Organization; address.AppendChild(Organization); System.Xml.XmlElement Address1 = doc.CreateElement("Address1"); Address1.InnerXml = a._Address1; address.AppendChild(Address1); System.Xml.XmlElement Address2 = doc.CreateElement("Address2"); Address2.InnerXml = a._Address2; address.AppendChild(Address2); System.Xml.XmlElement Address3 = doc.CreateElement("Address3"); Address3.InnerXml = a._Address3; address.AppendChild(Address3); System.Xml.XmlElement City = doc.CreateElement("City"); City.InnerXml = a._City; address.AppendChild(City); System.Xml.XmlElement State = doc.CreateElement("State"); State.InnerXml = a._State; address.AppendChild(State); System.Xml.XmlElement zip = doc.CreateElement("zip"); zip.InnerXml = a._Zip; address.AppendChild(zip); System.Xml.XmlElement country = doc.CreateElement("Country_non-US"); country.InnerXml = a._Country_nonUS; address.AppendChild(country); addresses.AppendChild(address); } doc.AppendChild(root); string xmlString = null; using (StringWriter stringWriter = new StringWriter()) { using (XmlWriter xmlTextWriter = XmlWriter.Create(stringWriter)) { doc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); xmlString = stringWriter.GetStringBuilder().ToString(); } } return(xmlString); }
public string createXMLBatchPost() { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null)); //create nodes System.Xml.XmlElement root = doc.CreateElement("batch"); //" <username>" & username & "</username>" & //" <password>" & password & "</password>" & //" <filename>" & fileName & "</filename>" & //" <appSignature>MyTest App</appSignature>" & System.Xml.XmlElement attr = doc.CreateElement("username"); attr.InnerXml = this._username; root.AppendChild(attr); attr = doc.CreateElement("password"); attr.InnerXml = this._password; root.AppendChild(attr); attr = doc.CreateElement("filename"); attr.InnerXml = this.pdf; root.AppendChild(attr); attr = doc.CreateElement("appSignature"); attr.InnerXml = ".NET SDK API"; root.AppendChild(attr); foreach (batchJob b in jobList) { dynamic job = doc.CreateElement("job"); attr = doc.CreateElement("startingPage"); attr.InnerXml = b.startingPage.ToString(); job.AppendChild(attr); attr = doc.CreateElement("endingPage"); attr.InnerXml = b.endingPage.ToString(); job.AppendChild(attr); dynamic printProductIOptions = doc.CreateElement("printProductionOptions"); job.AppendChild(printProductIOptions); //<documentClass>Letter 8.5 x 11</documentClass>" & //" <layout>Address on First Page</layout>" & //" <productionTime>Next Day</productionTime>" & //" <envelope>#10 Double Window</envelope>" & //" <color>Full Color</color>" & //" <paperType>White 24#</paperType>" & //" <printOption>Printing One side</printOption>" & //" <mailClass>First Class</mailClass>" & attr = doc.CreateElement("documentClass"); attr.InnerXml = b.documentClass; printProductIOptions.AppendChild(attr); attr = doc.CreateElement("layout"); attr.InnerXml = b.layout; printProductIOptions.AppendChild(attr); attr = doc.CreateElement("productionTime"); attr.InnerXml = b.productionTime; printProductIOptions.AppendChild(attr); attr = doc.CreateElement("envelope"); attr.InnerXml = b.envelope; printProductIOptions.AppendChild(attr); attr = doc.CreateElement("color"); attr.InnerXml = b.color; printProductIOptions.AppendChild(attr); attr = doc.CreateElement("paperType"); attr.InnerXml = b.paperType; printProductIOptions.AppendChild(attr); attr = doc.CreateElement("printOption"); attr.InnerXml = b.printOption; printProductIOptions.AppendChild(attr); attr = doc.CreateElement("mailClass"); attr.InnerXml = b.mailClass; printProductIOptions.AppendChild(attr); XmlElement addressList = doc.CreateElement("recipients"); job.AppendChild(addressList); foreach (addressItem ai in b.addressList) { XmlElement address = doc.CreateElement("address"); addressList.AppendChild(address); attr = doc.CreateElement("name"); if ((ai._First_name.Length > 0 & ai._Last_name.Length > 0)) { attr.InnerText = ai._Last_name + ", " + ai._First_name; } else { attr.InnerText = (ai._First_name + " " + ai._Last_name).Trim(); } address.AppendChild(attr); attr = doc.CreateElement("organization"); attr.InnerText = ai._Organization.Trim(); address.AppendChild(attr); attr = doc.CreateElement("address1"); attr.InnerText = ai._Address1.Trim(); address.AppendChild(attr); attr = doc.CreateElement("address2"); attr.InnerText = ai._Address2.Trim(); address.AppendChild(attr); attr = doc.CreateElement("address3"); attr.InnerText = ""; address.AppendChild(attr); attr = doc.CreateElement("city"); attr.InnerText = ai._City.Trim(); address.AppendChild(attr); attr = doc.CreateElement("state"); attr.InnerText = ai._State.Trim(); address.AppendChild(attr); attr = doc.CreateElement("postalCode"); attr.InnerText = ai._Zip.Trim();; address.AppendChild(attr); attr = doc.CreateElement("country"); attr.InnerText = (ai._Country_nonUS).Trim();; address.AppendChild(attr); } root.AppendChild(job); } doc.AppendChild(root); //doc.Declaration = New XDeclaration("1.0", "utf-8", Nothing) string xmlString = null; using (StringWriter stringWriter = new StringWriter()) { using (XmlWriter xmlTextWriter = XmlWriter.Create(stringWriter)) { doc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); xmlString = stringWriter.GetStringBuilder().ToString(); } } return(xmlString); }
public Validation.SchematronOutput.schematronoutput Validate(Stream xmlstream, Stream schematronstream) { /////////////////////////////// // Transform original Schemtron /////////////////////////////// string path = AppDomain.CurrentDomain.BaseDirectory; Uri schematronxsl = new Uri(@"file:\\" + path + @"\xsl_2.0\iso_svrl_for_xslt2.xsl"); Stream schematrontransform = new Validation.XSLTransform().Transform(schematronstream, schematronxsl); /////////////////////////////// // Apply Schemtron xslt /////////////////////////////// Stream results = new Validation.XSLTransform().Transform(xmlstream, schematrontransform); results.Position = 0; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(results); var nodes = doc.ChildNodes[1].ChildNodes; System.Xml.XmlNode activepattern = null; System.Xml.XmlNode firedrule = null; System.Xml.XmlNode failedassert = null; List <System.Xml.XmlNode> nodesclone = new List <System.Xml.XmlNode>(); foreach (System.Xml.XmlNode node in nodes) { nodesclone.Add(node); } foreach (System.Xml.XmlNode node in nodesclone) { if (node.Name == "svrl:active-pattern") { activepattern = node; } if (node.Name == "svrl:fired-rule") { firedrule = node; activepattern.AppendChild(firedrule); } if (node.Name == "svrl:failed-assert") { failedassert = node; firedrule.AppendChild(failedassert); } } //System.IO.StreamReader rd2 = new System.IO.StreamReader(results); //string xsltSchematronResult = rd2.ReadToEnd(); //xsltSchematronResult = xsltSchematronResult.Replace("schematron-output", "schematronoutput"); MemoryStream ms = new MemoryStream(); System.Xml.XmlWriter w = System.Xml.XmlWriter.Create(ms); ms.Position = 0; doc.WriteTo(w); w.Flush(); return(Serialization.DerializeXML <Validation.SchematronOutput.schematronoutput>(ms)); }