public CreateXmlDeclaration ( String version, string encoding, string standalone ) : |
||
version | String | |
encoding | string | |
standalone | string | |
Результат |
void Save() { var doc = new System.Xml.XmlDocument(); var xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); var root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); var records = doc.CreateElement("records"); doc.AppendChild(records); var tables = doc.CreateElement(string.Empty, "tables", string.Empty); var singleRecords = doc.CreateElement(string.Empty, "srec", string.Empty); var teamRecords = doc.CreateElement(string.Empty, "trec", string.Empty); records.AppendChild(singleRecords); records.AppendChild(teamRecords); records.AppendChild(tables); // single records: foreach (var s in this.mSingleStorage) { var r = doc.CreateElement(string.Empty, "record", string.Empty); var dsvId = doc.CreateAttribute("id"); dsvId.Value = s.SwimmerId; r.Attributes.Append(dsvId); } }
public static void Save() { if (File.Exists(sourceFile)) File.Delete(sourceFile); XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", "no"); doc.AppendChild(dec); XmlElement data = doc.CreateElement("usync.data"); XmlElement content = doc.CreateElement("content"); foreach (KeyValuePair<Guid, Tuple<string, int>> info in source) { XmlElement p = doc.CreateElement("info"); p.SetAttribute("guid", info.Key.ToString()); p.SetAttribute("name", info.Value.Item1); p.SetAttribute("parent", info.Value.Item2.ToString()); content.AppendChild(p); } data.AppendChild(content); doc.AppendChild(data); doc.Save(sourceFile); }
public static XmlDocument CreateXmlDocument() { XmlDocument doc = new XmlDocument(); XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", ""); doc.InsertBefore(decl, doc.DocumentElement); return doc; }
/// <summary> /// Saves the current collection of Host Instances to disk /// </summary> /// <param name="xmlDocName">Filename (verbatim) to save data to - User AppData Path is prepended /// if the path does not start with either ?: or \\</param> public virtual void ToXml(String xmlDocName) { System.Xml.XmlDocument xmlData = new System.Xml.XmlDocument(); // Create the XML Declaration (well formed) XmlDeclaration xmlDeclaration = xmlData.CreateXmlDeclaration("1.0", "utf-8", null); xmlData.InsertBefore(xmlDeclaration, xmlData.DocumentElement); // Create the root element System.Xml.XmlElement xmlRoot = xmlData.CreateElement("Hosts"); // Loop through the collection and serialize the lot foreach (KeyValuePair <String, Base> de in this) { Base fi = (Base)de.Value; XmlDocument xmlDoc = fi.ToXml(); foreach (XmlNode xn in xmlDoc.ChildNodes) { xmlRoot.AppendChild(xmlData.ImportNode(xn, true)); } } xmlData.AppendChild(xmlRoot); // Save the XML stream to the file if ((xmlDocName.Substring(1, 1) == ":") || (xmlDocName.StartsWith("\\\\"))) { xmlData.Save(xmlDocName); } else { xmlData.Save(Preferences.PreferenceSet.Instance.AppDataPath + "\\" + xmlDocName); } }
public TraceToXML(Point beginPoint, String penColor, String penWidth) { this.beginPoint = beginPoint; //创建 XML 对象 xmlDocument = new XmlDocument(); //声明 XML xmlDeclare = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", null); //创建根节点 elementRoot = xmlDocument.CreateElement("Trace"); xmlDocument.AppendChild(elementRoot); //创建第一个节点 //创建节点 Section elementSection = xmlDocument.CreateElement("Section"); elementSection.SetAttribute("penColor", penColor); elementSection.SetAttribute("penWidth", penWidth); elementRoot.AppendChild(elementSection); //创建 Section 的子节点 Point XmlElement elementPoint = xmlDocument.CreateElement("Point"); elementPoint.SetAttribute("time", "0"); XmlElement elementX = xmlDocument.CreateElement("X"); elementX.InnerText = beginPoint.X.ToString(); elementPoint.AppendChild(elementX); XmlElement elementY = xmlDocument.CreateElement("Y"); elementY.InnerText = beginPoint.Y.ToString(); elementPoint.AppendChild(elementY); elementSection.AppendChild(elementPoint); }
public XmlDocument GenerateForGenerateSolution(string platform, IEnumerable<XmlElement> projectElements) { var doc = new XmlDocument(); doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null)); var input = doc.CreateElement("Input"); doc.AppendChild(input); var generation = doc.CreateElement("Generation"); var platformName = doc.CreateElement("Platform"); platformName.AppendChild(doc.CreateTextNode(platform)); var hostPlatformName = doc.CreateElement("HostPlatform"); hostPlatformName.AppendChild(doc.CreateTextNode(_hostPlatformDetector.DetectPlatform())); generation.AppendChild(platformName); generation.AppendChild(hostPlatformName); input.AppendChild(generation); var featuresNode = doc.CreateElement("Features"); foreach (var feature in _featureManager.GetAllEnabledFeatures()) { var featureNode = doc.CreateElement(feature.ToString()); featureNode.AppendChild(doc.CreateTextNode("True")); featuresNode.AppendChild(featureNode); } input.AppendChild(featuresNode); var projects = doc.CreateElement("Projects"); input.AppendChild(projects); foreach (var projectElem in projectElements) { projects.AppendChild(doc.ImportNode(projectElem, true)); } return doc; }
public OpenFileForm(String path) { //create contact.xml while opening the OpenFile Dialog first time kChatFileFolderPath = path; if (!Directory.Exists(kChatFileFolderPath + "Common Files")) { Directory.CreateDirectory(kChatFileFolderPath + "Common Files"); } if (!File.Exists(kChatFileFolderPath + "Common Files\\contact.xml")) { try { XmlDocument contact = new XmlDocument(); XmlDeclaration dec = contact.CreateXmlDeclaration("1.0", "UTF-8", null); contact.AppendChild(dec); XmlElement root = contact.CreateElement("contactlist"); contact.AppendChild(root); XmlElement group = contact.CreateElement("group"); group.SetAttribute("name", "default"); root.AppendChild(group); contact.Save(kChatFileFolderPath + "Common Files\\contact.xml"); } catch (IOException ex) { MessageBox.Show(ex.ToString(), "IOError"); return; } } InitializeComponent(); }
/// <summary> /// Serializes the specified play list items. /// </summary> /// <param name="items">The play list.</param> /// <returns>The serielized play list as xml document.</returns> public XmlDocument Serialize(IEnumerable<ListViewItem> items) { var doc = new XmlDocument(); XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", "yes"); doc.AppendChild(declaration); XmlElement root = doc.CreateElement("items"); doc.AppendChild(root); foreach (ListViewItem item in items) { XmlElement element = doc.CreateElement("item"); element.InnerText = item.Text; XmlAttribute startTime = doc.CreateAttribute("start"); startTime.InnerText = item.SubItems[1].Text; element.Attributes.Append(startTime); XmlAttribute endTime = doc.CreateAttribute("end"); endTime.InnerText = item.SubItems[2].Text; element.Attributes.Append(endTime); XmlAttribute duration = doc.CreateAttribute("duration"); duration.InnerText = item.SubItems[3].Text; element.Attributes.Append(duration); root.AppendChild(element); } return doc; }
public static void Save() { try { if (!Directory.Exists(SettingsFolder)) { Directory.CreateDirectory(SettingsFolder); } System.Xml.XmlDocument Xml = new System.Xml.XmlDocument(); Xml.AppendChild(Xml.CreateXmlDeclaration("1.0", "utf-8", null)); XmlNode Pnode = Xml.CreateElement("Settings"); XmlNode Temp; Temp = Xml.CreateElement("GradientTop"); Temp.InnerText = ColorTranslator.ToHtml(GradientTopColor); Pnode.AppendChild(Temp); Temp = Xml.CreateElement("GradientBottom"); Temp.InnerText = ColorTranslator.ToHtml(GradientBottomColor); Pnode.AppendChild(Temp); Temp = Xml.CreateElement("OutlineColor"); Temp.InnerText = ColorTranslator.ToHtml(OutlineColor); Pnode.AppendChild(Temp); Temp = Xml.CreateElement("TextColor"); Temp.InnerText = ColorTranslator.ToHtml(TextColor); Pnode.AppendChild(Temp); Xml.AppendChild(Pnode); Xml.Save(SettingsPath); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message, "An Error Occured"); } }
public string InvokeResponse(string funcName, List<UPnPArg> args) { XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null); doc.AppendChild(dec); XmlElement env = doc.CreateElement("s", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/"); doc.AppendChild(env); env.SetAttribute("encodingStyle", "http://schemas.xmlsoap.org/soap/envelope/", "http://schemas.xmlsoap.org/soap/encoding/"); XmlElement body = doc.CreateElement("Body", "http://schemas.xmlsoap.org/soap/envelope/"); body.Prefix = "s"; env.AppendChild(body); XmlElement func = doc.CreateElement("u", funcName + "Response", "urn:schemas-upnp-org:service:AVTransport:1"); body.AppendChild(func); func.SetAttribute("xmlns:u", "urn:schemas-upnp-org:service:AVTransport:1"); if (args != null) { foreach (UPnPArg s in args) { XmlElement f = doc.CreateElement(s.ArgName); func.AppendChild(f); f.InnerText = s.ArgVal; } } //Saved for debugging: doc.Save(@"InvokeResponse.xml"); string msg = AppendHead(doc.OuterXml); return msg; }
public ControlResponse GetResponse(Exception ex) { var env = new XmlDocument(); env.AppendChild(env.CreateXmlDeclaration("1.0", "utf-8", "yes")); var envelope = env.CreateElement("SOAP-ENV", "Envelope", NS_SOAPENV); env.AppendChild(envelope); envelope.SetAttribute("encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/"); var rbody = env.CreateElement("SOAP-ENV:Body", NS_SOAPENV); env.DocumentElement.AppendChild(rbody); var fault = env.CreateElement("SOAP-ENV", "Fault", NS_SOAPENV); var faultCode = env.CreateElement("faultcode"); faultCode.InnerText = "500"; fault.AppendChild(faultCode); var faultString = env.CreateElement("faultstring"); faultString.InnerText = ex.ToString(); fault.AppendChild(faultString); var detail = env.CreateDocumentFragment(); detail.InnerXml = "<detail><UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\"><errorCode>401</errorCode><errorDescription>Invalid Action</errorDescription></UPnPError></detail>"; fault.AppendChild(detail); rbody.AppendChild(fault); return new ControlResponse { Xml = env.OuterXml, IsSuccessful = false }; }
public static XmlDocument CreateXMLDocument() { XmlDocument doc = new XmlDocument(); XmlNode docNode = doc.CreateXmlDeclaration("1.0", null, null); doc.AppendChild(docNode); XmlNode configurationNode = doc.CreateElement("Configuration"); doc.AppendChild(configurationNode); XmlNode hostNode = doc.CreateNode(XmlNodeType.Element, "host", ""); hostNode.InnerText = "https://testserver.datacash.com/Transaction"; XmlNode timeoutNode = doc.CreateNode(XmlNodeType.Element, "timeout", ""); timeoutNode.InnerText = "500"; XmlNode proxyNode = doc.CreateNode(XmlNodeType.Element, "proxy", ""); proxyNode.InnerText = "http://bloxx.dfguk.com:8080"; XmlNode logfileNode = doc.CreateNode(XmlNodeType.Element, "logfile", ""); logfileNode.InnerText = @"C:\Inetpub\wwwroot\WSDataCash\log.txt"; XmlNode loggingNode = doc.CreateNode(XmlNodeType.Element, "logging", ""); loggingNode.InnerText = "1"; configurationNode.AppendChild(hostNode); configurationNode.AppendChild(timeoutNode); configurationNode.AppendChild(proxyNode); configurationNode.AppendChild(logfileNode); configurationNode.AppendChild(loggingNode); return doc; }
public void AddAttachmentPlaceHolder(string actualPath, string placeholderPath) { var placeholderDocument = new XmlDocument(); placeholderDocument.CreateXmlDeclaration("1.0", "utf-16", "yes"); XmlNode rootNode = placeholderDocument.CreateNode(XmlNodeType.Element, "ManagedAttachment", string.Empty); XmlNode actualPathNode = placeholderDocument.CreateNode(XmlNodeType.Element, "ActualPath", string.Empty); XmlNode placeholderNode = placeholderDocument.CreateNode(XmlNodeType.Element, "PlaceholderPath", string.Empty); actualPathNode.InnerText = actualPath; placeholderNode.InnerText = placeholderPath; rootNode.AppendChild(actualPathNode); rootNode.AppendChild(placeholderNode); placeholderDocument.AppendChild(rootNode); using (var ms = new MemoryStream()) { ms.Position = 0; placeholderDocument.Save(ms); ms.Flush(); ms.Position = 0; var sr = new StreamReader(ms); string xml = sr.ReadToEnd(); string filecontents = LargeAttachmentHelper.FileTag + xml; File.WriteAllText(placeholderPath, filecontents, Encoding.Unicode); } }
private static string BuildFileContent() { var pages = ProjectProvider.Instance.GetSiteMapItems(); var doc = new XmlDocument(); doc.CreateXmlDeclaration("1.0", "UTF-8", string.Empty); var rootElem = doc.CreateElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9"); var langsWithSlash = LanguageTypeHelper.Instance.GetIsoNames().Select(iso => "http://" + SiteConfiguration.ProductionHostName + "/" + iso).ToArray(); foreach (var page in pages) { foreach (var lang in langsWithSlash) { var url = doc.CreateElement("url"); var location = doc.CreateElement("loc"); location.InnerText = lang + page.Location; url.AppendChild(location); var lastmod = doc.CreateElement("lastmod"); lastmod.InnerText = page.LastMod.ToString("yyyy-MM-dd"); url.AppendChild(lastmod); var changefreq = doc.CreateElement("changefreq"); changefreq.InnerText = page.ChangeFreq.ToString().ToLower(); url.AppendChild(changefreq); var priority = doc.CreateElement("priority"); priority.InnerText = page.Priority.ToString(CultureInfo.InvariantCulture); url.AppendChild(priority); rootElem.AppendChild(url); } } doc.AppendChild(rootElem); return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + doc.InnerXml .Replace("urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"", "urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\"") .Replace("<url xmlns=\"\">", "<url>"); }
public void Initiate() { try { string timelineFolder = Environment.CurrentDirectory + "/Timelines"; if (!Directory.Exists(timelineFolder)) { Directory.CreateDirectory(timelineFolder); } string fileName = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".xml"; xmlDoc = new XmlDocument(); XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); //create root XmlElement rootNode = xmlDoc.CreateElement("TIMELINE"); xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); xmlDoc.AppendChild(rootNode); string fullFilePath = timelineFolder + "/" + fileName; currentFileName = fullFilePath; if (!File.Exists(fullFilePath)) { FileStream fs = File.Create(fullFilePath); fs.Close(); } xmlDoc.Save(fullFilePath); } catch (Exception ex) { Utilities.UtilitiesLib.LogError(ex); } }
public static string GetPartInfoXMLRequest(string cliinfo,string productid) { XmlDocument doc = new XmlDocument(); XmlElement root,node,node_1; XmlDeclaration dec; // doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.AppendChild(dec= doc.CreateXmlDeclaration("1.0", "", "")); root= doc.CreateElement("REQ"); doc.AppendChild(root); node= doc.CreateElement("CLIINFO"); node.InnerText = cliinfo; root.AppendChild(node); node = doc.CreateElement("FUNCTION"); node.InnerText="PT000V_PartInfo"; root.AppendChild(node); node = doc.CreateElement("VERSION"); node.InnerText = "1.0.0.0"; root.AppendChild(node); node=doc.CreateElement("ELE"); XmlAttribute attr=doc.CreateAttribute("NAME"); attr.Value="PARTINFO"; node.Attributes.Append(attr); attr = doc.CreateAttribute("NAME"); attr.Value = "PARTINFO"; node_1=doc.CreateElement("ATTR"); node_1.Attributes.Append(attr); node_1.InnerText=productid; node.AppendChild(node_1); root.AppendChild(node); return doc.InnerXml; }
public void CreateXml(string xmlPath, string xmlName, string[] value, string[] xmlElementNode) { try { string str = inType.ToString(); if (str.Length < 5) { return; } string rootName = str.Substring(str.Length - 5, 4); XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(dec); XmlElement root = doc.CreateElement(rootName); doc.AppendChild(root); XmlNode childElement = doc.CreateElement(str); for (int i = 0; i < xmlElementNode.Length; i++) { XmlElement xe = doc.CreateElement(xmlElementNode[i]); xe.InnerText = value[i]; childElement.AppendChild(xe); } root.AppendChild(childElement); doc.Save(string.Concat(@"", xmlPath, xmlName)); } catch (Exception e) { throw e; } }
/// <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(); } }
public static XmlDocument CreateXmlDocument() { var document = new XmlDocument(); var newChild = document.CreateXmlDeclaration("1.0", "utf-8", string.Empty); document.AppendChild(newChild); return document; }
public static TreeNodeCollection BuildTreeNodes(bool refreshSiteMap) { XmlDocument map = null; XmlElement root = null; XmlElement examplesNode = null; if (refreshSiteMap) { map = new XmlDocument(); XmlDeclaration dec = map.CreateXmlDeclaration("1.0", "utf-8", null); map.AppendChild(dec); root = map.CreateElement("siteMap"); root.SetAttribute("xmlns", "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"); map.AppendChild(root); examplesNode = map.CreateElement("siteMapNode"); examplesNode.SetAttribute("title", "Examples"); root.AppendChild(examplesNode); } string path = HttpContext.Current.Server.MapPath("~/Examples/"); TreeNodeCollection result = BuildTreeLevel(new DirectoryInfo(path), 1, 3, examplesNode); if (root != null && root.ChildNodes.Count > 0) { map.Save(HttpContext.Current.Server.MapPath("Web.sitemap")); } return result; }
private static System.Xml.XmlDocument CreateFileExpirationsFile(System.Xml.XmlDocument doc, ref SQLOptions o) { string FileName = GetCacheFilePath("cache_expirations"); if (doc == null) { doc = new System.Xml.XmlDocument(); System.Xml.XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "ASCII", "yes"); doc.AppendChild(dec); System.Xml.XmlElement ele = doc.CreateElement("SQLHelper_FileExpirations"); doc.AppendChild(ele); } //General.IO.IOTools.QueueWriteFile(doc,FileName, "cache_expirations", new General.IO.IOTools.QueueWriteFileCompletedCallback(CreateFileExpirationsFileCallback)); try { o.WriteToLog("saving cache_expirations.xml"); doc.Save(FileName); } catch (System.UnauthorizedAccessException) { o.WriteToLog("failure to save cache_expirations.xml"); //DO NOTHING } return(doc); }
XmlDocument CreateXML(string result, Track[] items = null) { XmlDocument xmldoc = new XmlDocument(); XmlDeclaration decl = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null); xmldoc.AppendChild(decl); XmlNode root = xmldoc.CreateElement("HttpResponse"); xmldoc.AppendChild(root); XmlNode res = xmldoc.CreateElement("Result"); res.InnerText = result; root.AppendChild(res); XmlNode args = xmldoc.CreateElement("Params"); root.AppendChild(args); if (items!=null) { for (int i = 0; i < items.Length; i++) { XmlNode node = xmldoc.CreateElement("Song"); args.AppendChild(node); XmlNode name = xmldoc.CreateElement("Name"); name.InnerText = items[i].Name; XmlNode title = xmldoc.CreateElement("Title"); title.InnerText = items[i].Title; XmlNode filestream = xmldoc.CreateElement("FileStream"); filestream.InnerText = items[i].FileStream; node.AppendChild(name); node.AppendChild(title); node.AppendChild(filestream); } } return xmldoc; }
private void btn_OK_Click(object sender, EventArgs e) { XmlDocument xmlDoc = new XmlDocument(); XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); xmlDoc.AppendChild(docNode); XmlNode version = xmlDoc.CreateElement("version"); xmlDoc.AppendChild(version); XmlNode sbtNode = xmlDoc.CreateElement("SBT"); XmlAttribute sbtAttribute = xmlDoc.CreateAttribute("Path"); sbtAttribute.Value = textBox1.Text; sbtNode.Attributes.Append(sbtAttribute); version.AppendChild(sbtNode); XmlNode garenaNode = xmlDoc.CreateElement("Garena"); XmlAttribute garenaAttribute = xmlDoc.CreateAttribute("Path"); garenaAttribute.Value = textBox2.Text; garenaNode.Attributes.Append(garenaAttribute); version.AppendChild(garenaNode); XmlNode superNode = xmlDoc.CreateElement("Super"); XmlAttribute superAttribute = xmlDoc.CreateAttribute("Path"); superAttribute.Value = textBox3.Text; superNode.Attributes.Append(superAttribute); version.AppendChild(superNode); xmlDoc.Save("path"); this.Close(); }
private XmlDocument CreateMessage(string data, object recipients) { var doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); XmlElement e0 = doc.CreateElement(string.Empty, "Message", string.Empty); doc.AppendChild(e0); XmlElement e2 = doc.CreateElement(string.Empty, "Data", string.Empty); e2.AppendChild(doc.CreateTextNode(data)); e0.AppendChild(e2); XmlElement e3 = doc.CreateElement(string.Empty, "Recipients", string.Empty); e0.AppendChild(e3); foreach (string s in ObjectToStringArray(recipients)) { XmlElement e4 = doc.CreateElement(string.Empty, "Recipient", string.Empty); e4.AppendChild(doc.CreateTextNode(s)); e3.AppendChild(e4); } return doc; }
private static void _processDocument(XmlNode document, StreamWriter sw) { XmlDocument docNode = new XmlDocument(); XmlDeclaration xmlDeclaration = docNode.CreateXmlDeclaration("1.0", "cp866", null); docNode.InsertBefore(xmlDeclaration, docNode.DocumentElement); XmlElement docRoot = (XmlElement)docNode.ImportNode(document, true); docNode.AppendChild(docRoot); Regex rgx = new Regex("<(\\w+)>"); String s = rgx.Replace(docNode.OuterXml, "<$1 xmlns=\"itek\">"); s = s.Replace("<Документ xmlns=\"itek\">", "<Документ>"); s = s.Replace("РаботыЧужие", "true"); eurocarService.Документ documentRequest = (eurocarService.Документ)_x.Deserialize(new System.IO.StringReader(s)); try { sw.WriteLine(DateTime.Now.ToString() + " Отправка документа " + documentRequest.Номер); _cl.PutDoc(documentRequest); } catch (ProtocolException e) { // Silently except it... } }
public void Save(string fileName) { XmlDocument doc = new XmlDocument(); XmlNode declNode = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.AppendChild(declNode); var regNode = doc.CreateElement(@"Реестр"); doc.AppendChild(regNode); var packNode = doc.CreateElement(@"Пакет"); regNode.AppendChild(packNode); var recipNode = doc.CreateElement(@"Получатель"); recipNode.SetAttribute("ИНН", RecipientINN); recipNode.SetAttribute("КПП", RecipientKPP); packNode.AppendChild(recipNode); var sendNode = doc.CreateElement(@"Отправитель"); sendNode.SetAttribute("ИНН", SenderINN); sendNode.SetAttribute("КПП", SenderKPP); packNode.AppendChild(sendNode); foreach (var attachment in _Attachments) { var attNode = doc.CreateElement(@"Вложение"); attNode.SetAttribute("ИмяФайла", attachment); packNode.AppendChild(attNode); } doc.Save(fileName); }
private static XmlDocument getXmlDoc() { XmlDocument xmlDoc; try { xmlDoc = new XmlDocument(); xmlDoc.Load(CONFIG_PATH); } catch { string dest = DateTime.Now.ToFileTime().ToString(); if (File.Exists(CONFIG_PATH)) { File.Move(CONFIG_PATH, dest); MessageBox.Show("配置已损坏!将使用默认配置\n原配置文件已被重命名为" + dest, "警告"); } xmlDoc = new XmlDocument(); xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"); XmlNode root = xmlDoc.CreateElement("config"); XmlNode defaultPath = xmlDoc.CreateElement("path"); XmlCDataSection cdata = xmlDoc.CreateCDataSection(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); defaultPath.AppendChild(cdata); root.AppendChild(defaultPath); xmlDoc.AppendChild(root); } return xmlDoc; }
private void CreateBasicRssDoc(XmlDocument doc, string title, string description, string link) { XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(declaration, doc.DocumentElement); XmlElement rssNode = doc.CreateElement("rss"); XmlAttribute rssAtt = doc.CreateAttribute("version"); rssAtt.Value = "2.0"; rssNode.Attributes.Append(rssAtt); XmlElement channelNode = doc.CreateElement("channel"); XmlElement titleNode = doc.CreateElement("title"); titleNode.InnerText = title; channelNode.AppendChild(titleNode); XmlElement desNode = doc.CreateElement("description"); desNode.InnerText = description; channelNode.AppendChild(desNode); XmlElement linkNode = doc.CreateElement("link"); linkNode.InnerText = link; channelNode.AppendChild(linkNode); rssNode.AppendChild(channelNode); doc.AppendChild(rssNode); }
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; }
public static void SaveToDisk() { if (File.Exists(pairFile)) File.Delete(pairFile); XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", "no"); doc.AppendChild(dec); XmlElement data = doc.CreateElement("usync.data"); XmlElement content = doc.CreateElement("content"); foreach (KeyValuePair<Guid, Guid> pair in pairs) { XmlElement p = doc.CreateElement("pair"); p.SetAttribute("id", pair.Key.ToString()); p.SetAttribute("guid", pair.Value.ToString()); content.AppendChild(p); } data.AppendChild(content); doc.AppendChild(data); doc.Save(pairFile); }
private static XmlDeclaration AppendDecleration(XmlDocument xmlDoc) { // Write down the XML declaration XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); return xmlDeclaration; }
/// <summary> /// XML-Datei mit XmlDocument erstellen. /// </summary> static void CreateXmlDocument() { XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration declaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "no"); // XML Deklaration xmlDoc.AppendChild(declaration); XmlNode rootNode = xmlDoc.CreateElement("books"); // Wurzelelement xmlDoc.AppendChild(rootNode); // Wurzelelement zum Dokument hinzufuegen // <book> Element XmlNode userNode = xmlDoc.CreateElement("book"); // mit einem Attribut XmlAttribute attribute = xmlDoc.CreateAttribute("release"); attribute.Value = "2013/02/15"; userNode.Attributes.Append(attribute); // Attribut zum <book> Ele hinzufuegen // und Textinhalt userNode.InnerText = "Elizabeth Corley - Pretty Little Things"; rootNode.AppendChild(userNode); // Textinhalt zum <book> Ele hinzufuegen // und noch ein <book> userNode = xmlDoc.CreateElement("book"); attribute = xmlDoc.CreateAttribute("release"); attribute.Value = "2011/11/11"; userNode.Attributes.Append(attribute); userNode.InnerText = "Stephen Hawking - A Brief History Of Time"; rootNode.AppendChild(userNode); // XML Dokument speichern xmlDoc.Save("xmlDocument_books.xml"); // in ../projectname/bin/debug/ }
private void GenerateStrings(string inputPath, string outputFile) { XElement rootElement = XElement.Load(inputPath); IEnumerable<Tuple<string, string>> items = from dataElement in rootElement.Descendants("data") let key = dataElement.Attribute("name").Value let valueElement = dataElement.Element("value") where valueElement != null let value = valueElement.Value select new Tuple<string, string>(key, value); XmlDocument document = new XmlDocument(); document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-8", null)); XmlNode rootNode = document.CreateElement("resources"); document.AppendChild(rootNode); foreach (var pair in items) { XmlNode elementNode = document.CreateElement("string"); elementNode.InnerText = processValue(pair.Item2); XmlAttribute attributeName = document.CreateAttribute("name"); attributeName.Value = processKey(pair.Item1); // ReSharper disable once PossibleNullReferenceException elementNode.Attributes.Append(attributeName); rootNode.AppendChild(elementNode); } document.Save(outputFile); }
public static bool Init(string spath) { lock(CExceptionContainer_WuQi.obj_lock) { if (false != CExceptionContainer_WuQi.b_initguid) return true; CExceptionContainer_WuQi.s_xmlfilepath = spath+"\\exceptionstore.xml"; //删除以前的异常信息记录,也可考虑更名保存 if (File.Exists(CExceptionContainer_WuQi.s_xmlfilepath)) { File.Delete(CExceptionContainer_WuQi.s_xmlfilepath); } //新建异常信息存储文件 XmlDocument xmldoc = new XmlDocument(); XmlDeclaration declaration = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null); xmldoc.AppendChild(declaration); XmlNode rootnode = xmldoc.CreateNode(XmlNodeType.Element, "exceptions", null); xmldoc.AppendChild(rootnode); xmldoc.Save(CExceptionContainer_WuQi.s_xmlfilepath); CExceptionContainer_WuQi.l_exception = new List<CExceptionInfo_WuQi>(); //存储发生异常时向用户提供的信息,约定从 1 开始。 CExceptionContainer_WuQi.dictionary_msg = new Dictionary<int, string>(); CExceptionContainer_WuQi.dictionary_msg.Add(0, "异常管理系统发生故障!请与系统管理人员联系。"); CExceptionContainer_WuQi.dictionary_msg.Add(1, "对不起,系统发生故障!请与系统管理人员联系。"); CExceptionContainer_WuQi.b_initguid = true; return CExceptionContainer_WuQi.b_initguid; } }
public string ew_savepagexml(string pageName, string subFolder, XPathNavigator content) { try { string wikiFolder = getmodulesetting("wikiFolder").ToString(); string pagePath = string.Empty; string sPath = string.Empty; string phisicalRoot = transformer.DnnSettings.P.HomeDirectoryMapPath; // phisical portal home directory if (!phisicalRoot.EndsWith("\\")) { phisicalRoot += "\\"; } //optional subFolder (currently used only for archived versions in "archive" folder) if (subFolder != string.Empty) { sPath = wikiFolder + @"\" + subFolder; } else { sPath = wikiFolder; } //log("Check path " + System.IO.Path.Combine(phisicalRoot, sPath)); if (!Directory.Exists(System.IO.Path.Combine(phisicalRoot, sPath))) { Directory.CreateDirectory(System.IO.Path.Combine(phisicalRoot, sPath)); } pagePath = sPath + @"\" + pageName; if (!pagePath.ToLower().EndsWith(".wiki.xml")) { pagePath += ".wiki.xml"; } System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); XmlDeclaration xmldecl; xmldecl = doc.CreateXmlDeclaration("1.0", null, null); doc.LoadXml(content.OuterXml); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmldecl, root); //log("Save page to " + System.IO.Path.Combine(phisicalRoot, pagePath)); doc.Save(System.IO.Path.Combine(phisicalRoot, pagePath)); return("ok"); } catch (Exception ex) { return(ex.Message); } }
public static void Write(string key, string value) { key = System.Web.HttpUtility.HtmlEncode(key); value = System.Web.HttpUtility.HtmlEncode(value); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); XmlNode root; if (!File.Exists(xml_path)) { doc.CreateXmlDeclaration("1.0", "utf-8", "yes"); root = doc.CreateElement("config"); XmlNode node = doc.CreateElement(key); node.InnerText = value; root.AppendChild(node); doc.AppendChild(root); doc.Save(xml_path); return; } doc.Load(xml_path); root = doc.DocumentElement; if (root == null) { root = doc.CreateElement("config"); doc.AppendChild(root); } XmlNode nod; try { nod = root.SelectSingleNode("/config/" + key); } catch (Exception e) { Console.WriteLine(e.Message.ToString()); return; } if (nod == null) { nod = doc.CreateElement(key); nod.InnerText = value; root.AppendChild(nod); doc.Save(xml_path); return; } if (nod.InnerText != value) { nod.InnerText = value; doc.Save(xml_path); } }
private void GenerateMetaData() { string MetaDataFileName = string.Format("{0}.MetaData.xml", Convert.ToString(this.cbxLanguages.SelectedValue).Trim()); string metadataFileFullName = productScreenshotDirectory + MetaDataFileName; XmlDocument doc = new System.Xml.XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null); doc.AppendChild(dec); // Create the root element XmlElement root = doc.CreateElement("screenshots"); doc.AppendChild(root); foreach (ProductImage screenshot in this.images) { XmlElement filename = doc.CreateElement(MetaDataNodeFileName); filename.InnerText = screenshot.Url; XmlElement description = doc.CreateElement(MetaDataNodeDescription); description.InnerText = screenshot.Description; XmlElement width = doc.CreateElement(MetaDataNodeWidth); width.InnerText = screenshot.ImageSize.Width.ToString(); XmlElement height = doc.CreateElement(MetaDataNodeHeight); height.InnerText = screenshot.ImageSize.Height.ToString(); XmlElement thumbfilename = doc.CreateElement(MetaDataNodeFileName); thumbfilename.InnerText = screenshot.Thumbnail.Url; XmlElement thumbtitle = doc.CreateElement(MetaDataNodeTitle); thumbtitle.InnerText = screenshot.Thumbnail.Title; XmlElement thumbnail = doc.CreateElement(MetaDataNodeThumbnail); thumbnail.AppendChild(thumbfilename); thumbnail.AppendChild(thumbtitle); XmlElement image = doc.CreateElement("image"); image.AppendChild(filename); image.AppendChild(description); image.AppendChild(width); image.AppendChild(height); image.AppendChild(thumbnail); root.AppendChild(image); } doc.Save(metadataFileFullName); }
private void SaveParameterFile() { string NowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); try { DataSet saveData = paramFile.Copy(); saveData.Tables["Device"].Rows[0]["UpdateTime"] = NowTime; saveData.Tables["Var"].Columns.Remove("Message_Name"); saveData.Tables["Var"].Columns.Remove("Var_Desc"); saveData.Tables["Var"].Columns.Remove("Var_Obj"); saveData.Tables["Var"].Columns.Remove("Tables"); saveData.Tables["Var"].Columns.Remove("Modify"); using (MemoryStream ms = new MemoryStream()) { saveData.WriteXml(ms); ms.Position = 0; XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(ms); XmlNode root = doc.SelectSingleNode("NewDataSet"); XmlNode device = root.SelectSingleNode("Device"); doc.RemoveChild(root); XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", "yes"); doc.AppendChild(declaration); doc.AppendChild(device); doc.Save(FileName); } } catch (Exception ex) { MessageBox.Show("保存定值文件失败!\n错误信息:" + ex.Message); return; } deviceTable.Rows[0]["UpdateTime"] = NowTime; this.textBoxCreateTime.Text = NowTime; foreach (DataRow var in varTable.Rows) { var["Modify"] = false; } SaveToolStripMenuItem.Enabled = false; ReloadToolStripMenuItem.Enabled = false; }
public void SaveRuleList(List <RewriterRule> ruleList) { System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); System.Xml.XmlDeclaration xmldecl; xmldecl = xml.CreateXmlDeclaration("1.0", "utf-8", null); xml.AppendChild(xmldecl); System.Xml.XmlElement xmlelem = xml.CreateElement("", "rewrite", ""); foreach (RewriterRule rule in ruleList) { System.Xml.XmlElement e = xml.CreateElement("", "item", ""); e.SetAttribute("lookfor", rule.LookFor); e.SetAttribute("sendto", rule.SendTo); xmlelem.AppendChild(e); } xml.AppendChild(xmlelem); xml.Save(HttpContext.Current.Server.MapPath(string.Format("//config/rewrite.config", "/"))); }
public static ISqlMapper CreateMapper() { System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); // for <?xml version="1.0" encoding="utf-8" ?> XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); xmlDoc.AppendChild(docNode); // root(sqlMapConfig) XmlElement sqlMapConfig = xmlDoc.CreateElement("sqlMapConfig"); sqlMapConfig.SetAttribute("xmlns", "http://ibatis.apache.org/dataMapper"); sqlMapConfig.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); xmlDoc.AppendChild(sqlMapConfig); // settings XmlElement settings = xmlDoc.CreateElement("settings", sqlMapConfig.NamespaceURI); sqlMapConfig.AppendChild(settings); XmlElement settings_useStatementNamespaces = xmlDoc.CreateElement("setting", sqlMapConfig.NamespaceURI); settings_useStatementNamespaces.SetAttribute("useStatementNamespaces", "false"); XmlElement settings_cacheModelsEnabled = xmlDoc.CreateElement("setting", sqlMapConfig.NamespaceURI); settings_cacheModelsEnabled.SetAttribute("cacheModelsEnabled", "true"); XmlElement settings_validateSqlMap = xmlDoc.CreateElement("setting", sqlMapConfig.NamespaceURI); settings_validateSqlMap.SetAttribute("validateSqlMap", "true"); settings.AppendChild(settings_useStatementNamespaces); settings.AppendChild(settings_cacheModelsEnabled); settings.AppendChild(settings_validateSqlMap); // providers XmlElement providers = xmlDoc.CreateElement("providers", sqlMapConfig.NamespaceURI); sqlMapConfig.AppendChild(providers); providers.SetAttribute("embedded", "configs.providers.config, iBatisNet.Biz"); // database XmlElement database = xmlDoc.CreateElement("database", sqlMapConfig.NamespaceURI); sqlMapConfig.AppendChild(database); XmlElement database_provider = xmlDoc.CreateElement("provider", sqlMapConfig.NamespaceURI); database_provider.SetAttribute("name", "sqlServer2.0"); XmlElement database_dataSource = xmlDoc.CreateElement("dataSource", sqlMapConfig.NamespaceURI); database_dataSource.SetAttribute("name", "MtBatisSQL"); database_dataSource.SetAttribute("connectionString", @"data source=(localDB)\MSSQLLocalDB;initial catalog=TEMP.BIZ.DB;integrated security=True;MultipleActiveResultSets=True;"); database.AppendChild(database_provider); database.AppendChild(database_dataSource); // sqlMaps XmlElement sqlMaps = xmlDoc.CreateElement("sqlMaps", sqlMapConfig.NamespaceURI); sqlMapConfig.AppendChild(sqlMaps); var queryFileNames = IBatisNetMapperHelper.GetAllQueryXML("Query"); var defaultNamespace = Assembly.GetExecutingAssembly().GetName().Name; foreach (var queryFile in queryFileNames) { XmlElement elem = xmlDoc.CreateElement("sqlMap", sqlMapConfig.NamespaceURI); elem.SetAttribute("embedded", $"{queryFile}, {defaultNamespace}"); sqlMaps.AppendChild(elem); } // test xmlDoc.Save("@test.xml"); // Instantiate Ibatis mapper using the XmlDocument via a Builder, // instead of Ibatis using the config file. DomSqlMapBuilder builder = new DomSqlMapBuilder(); ISqlMapper ibatisInstance = builder.Configure("@test.xml"); return(ibatisInstance); }
System.Xml.XmlDocument Decompress(byte[] buffer) { var decompressBuffer = Utils.Zlib.Decompress(buffer); var doc = new System.Xml.XmlDocument(); var reader = new Utl.BinaryReader(decompressBuffer); var keys = new Dictionary <Int16, string>(); Int16 keySize = -1; reader.Get(ref keySize); for (int i = 0; i < keySize; i++) { Int16 key = -1; string name = ""; reader.Get(ref name, Encoding.UTF8, false, 2); reader.Get(ref key); keys.Add(key, name); } var values = new Dictionary <Int16, string>(); Int16 valueSize = -1; reader.Get(ref valueSize); for (int i = 0; i < valueSize; i++) { Int16 key = -1; string value = ""; reader.Get(ref value, Encoding.UTF8, false, 2); reader.Get(ref key); values.Add(key, value); } Action <System.Xml.XmlNode> decomp = null; decomp = (node) => { Int16 elementSize = 0; reader.Get(ref elementSize); for (int i = 0; i < elementSize; i++) { Int16 nameKey = -1; reader.Get(ref nameKey); var element = doc.CreateElement(keys[nameKey]); node.AppendChild(element); bool isHaveValue = false; reader.Get(ref isHaveValue); if (isHaveValue) { Int16 value = -1; reader.Get(ref value); var valueNode = doc.CreateNode(System.Xml.XmlNodeType.Text, "", ""); valueNode.Value = values[value]; element.AppendChild(valueNode); } bool isHaveChildren = false; reader.Get(ref isHaveChildren); if (isHaveChildren) { decomp(element); } } }; var declare = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(declare); decomp(doc); return(doc); }
/// <summary> /// Saves a string to a resource file. /// </summary> /// <param name="key">The key to save (e.g. "MyWidget.Text").</param> /// <param name="value">The text value for the key.</param> /// <param name="resourceFileRoot">Relative path for the resource file root (e.g. "DesktopModules/Admin/Lists/App_LocalResources/ListEditor.ascx.resx").</param> /// <param name="language">The locale code in lang-region format (e.g. "fr-FR").</param> /// <param name="portalSettings">The current portal settings.</param> /// <param name="resourceType">Specifies whether to save as portal, host or system resource file.</param> /// <param name="createFile">if set to <c>true</c> a new file will be created if it is not found.</param> /// <param name="createKey">if set to <c>true</c> a new key will be created if not found.</param> /// <returns>If the value could be saved then true will be returned, otherwise false.</returns> /// <exception cref="System.Exception">Any file io error or similar will lead to exceptions</exception> public bool SaveString(string key, string value, string resourceFileRoot, string language, PortalSettings portalSettings, DotNetNuke.Services.Localization.LocalizationProvider.CustomizedLocale resourceType, bool createFile, bool createKey) { try { if (key.IndexOf(".", StringComparison.Ordinal) < 1) { key += ".Text"; } string resourceFileName = GetResourceFileName(resourceFileRoot, language); resourceFileName = resourceFileName.Replace("." + language.ToLower() + ".", "." + language + "."); switch (resourceType) { case DotNetNuke.Services.Localization.LocalizationProvider.CustomizedLocale.Host: resourceFileName = resourceFileName.Replace(".resx", ".Host.resx"); break; case DotNetNuke.Services.Localization.LocalizationProvider.CustomizedLocale.Portal: resourceFileName = resourceFileName.Replace(".resx", ".Portal-" + portalSettings.PortalId + ".resx"); break; } resourceFileName = resourceFileName.TrimStart('~', '/', '\\'); string filePath = HostingEnvironment.MapPath("~/" + Globals.ApplicationPath + resourceFileName); XmlDocument doc = null; if (File.Exists(filePath)) { doc = new XmlDocument(); doc.Load(filePath); } else { if (createFile) { doc = new System.Xml.XmlDocument(); doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes")); XmlNode root = doc.CreateElement("root"); doc.AppendChild(root); AddResourceFileNode(ref root, "resheader", "resmimetype", "text/microsoft-resx"); AddResourceFileNode(ref root, "resheader", "version", "2.0"); AddResourceFileNode(ref root, "resheader", "reader", "System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); AddResourceFileNode(ref root, "resheader", "writer", "System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); } } if (doc == null) { return(false); } XmlNode reskeyNode = doc.SelectSingleNode("root/data[@name=\"" + key + "\"]"); if (reskeyNode != null) { reskeyNode.SelectSingleNode("value").InnerText = value; } else { if (createKey) { XmlNode root = doc.SelectSingleNode("root"); AddResourceFileNode(ref root, "data", key, value); } else { return(false); } } doc.Save(filePath); DataCache.RemoveCache("/" + resourceFileName.ToLower()); return(true); } catch (Exception ex) { throw new Exception(string.Format("Error while trying to create resource in {0}", resourceFileRoot), ex); } }
private void CreateDefaultConfiguration() { // XML Declaration // <?xml version="1.0" encoding="utf-8"?> XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); xmlDoc.AppendChild(dec); // Create root node and append to the document // <configuration> XmlElement rootNode = xmlDoc.CreateElement(XMLROOT); xmlDoc.AppendChild(rootNode); // Create Configuration Sections node and add as the first node under the root // <configSections> XmlElement configNode = xmlDoc.CreateElement(CONFIGNODE); xmlDoc.DocumentElement.PrependChild(configNode); // Create the user settings section group declaration and append to the config node above // <sectionGroup name="userSettings"...> XmlElement groupNode = xmlDoc.CreateElement(GROUPNODE); groupNode.SetAttribute("name", USERNODE); Type type = typeof(System.Configuration.UserSettingsGroup); groupNode.SetAttribute("type", type.AssemblyQualifiedName); configNode.AppendChild(groupNode); // Create the Application section declaration and append to the groupNode above // <section name="AppName.Properties.Settings"...> XmlElement newSection = xmlDoc.CreateElement("section"); newSection.SetAttribute("name", APPNODE); type = typeof(System.Configuration.ClientSettingsSection); newSection.SetAttribute("type", type.AssemblyQualifiedName); newSection.SetAttribute("allowExeDefinition", "MachineToLocalUser"); newSection.SetAttribute("requirePermission", "false"); groupNode.AppendChild(newSection); XmlElement startupNode = xmlDoc.CreateElement("startup"); configNode.AppendChild(startupNode); XmlElement versionInfo = xmlDoc.CreateElement("supportedRuntime"); versionInfo.SetAttribute("version", Environment.Version.ToString(3)); startupNode.AppendChild(versionInfo); // Create the userSettings node and append to the root node // <userSettings> XmlElement userNode = xmlDoc.CreateElement(USERNODE); xmlDoc.DocumentElement.AppendChild(userNode); // Create the Application settings node and append to the userNode above // <AppName.Properties.Settings> XmlElement appNode = xmlDoc.CreateElement(APPNODE); userNode.AppendChild(appNode); try { xmlDoc.Save(GlobalConfig.KrentoConfigFileName); } catch { } }
/// <summary> /// Xmlファイル作成(年別休日) /// </summary> static void CreateXmlHolidayYear() { // 内閣府のHPからCSVを取得して、休日ファイルを作成 string address = @"https://www8.cao.go.jp/chosei/shukujitsu/syukujitsu_kyujitsu.csv"; var holidays = new List <Holiday>(); var request = System.Net.WebRequest.Create(address); using (var response = request.GetResponse()) { using (var stream = response.GetResponseStream()) { using (var reader = new System.IO.StreamReader(stream, Encoding.GetEncoding("Shift_JIS"))) { do { DateTime o; var items = reader.ReadLine().Split(','); if (DateTime.TryParse(items[0], out o)) { var holiday = new Holiday() { Name = items[1], Date = o }; holidays.Add(holiday); } } while (!reader.EndOfStream); } } } holidays.Select(x => x.Date.Year).Distinct().ForEach(nendo => { // フォルダの作成 if (!System.IO.Directory.Exists(Holiday.HolidayXmlFolder)) { System.IO.Directory.CreateDirectory(Holiday.HolidayXmlFolder); } string filePath = System.IO.Path.Combine(Holiday.HolidayXmlFolder, string.Concat(nendo.ToString(), ".xml")); // ファイルが存在するなら、処理しない if (System.IO.File.Exists(filePath)) { return; } // 既存のフォーマットに合わせるために、XMLファイルの構造を変更しない var xmlDocument = new System.Xml.XmlDocument(); var xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null); var eleHolidays = xmlDocument.CreateElement("Holidays"); xmlDocument.AppendChild(xmlDeclaration); xmlDocument.AppendChild(eleHolidays); holidays.Where(x => x.Date.Year == nendo).ForEach(y => { var eleHoliday = xmlDocument.CreateElement("Holiday"); var eleDay = xmlDocument.CreateElement("Day"); var eleName = xmlDocument.CreateElement("Name"); eleDay.InnerText = y.Date.ToString(); eleName.InnerText = y.Name; eleHoliday.AppendChild(eleDay); eleHoliday.AppendChild(eleName); eleHolidays.AppendChild(eleHoliday); }); xmlDocument.Save(filePath); }); }
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); }