public bool Intialize(string filename) { /* +=== Error check ===+ */ if (!File.Exists(filename)) { return(false); } active = true; /* Initial xml setup check */ mDoc = new XmlDocument(); mFilename = filename; settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; settings.IndentChars = "\t"; XmlElement root = mDoc.DocumentElement; if (!File.ReadAllText(mFilename).Contains(mCoreContainerName)) // if root node cannot be found, then it loads it in { XmlNode initNode = mDoc.CreateNode(XmlNodeType.Element, mCoreContainerName, null); mDoc.InsertAfter(initNode, root); XmlDeclaration xmlDecleration = mDoc.CreateXmlDeclaration("1.0", "UTF-8", null); mDoc.InsertAfter(xmlDecleration, root); mDoc.Save(filename); } return(active); }
public void escriuXML(XmlDocument xmlDoc, String nomFitxer) { // Utilitzem objectes de System.XML XmlNode xNodeArrel; XmlDeclaration xDeclaracio; XmlComment xComentari; // inserim la declaració sobre l'estàndard XML i la codificació, el "yes" indica que aquest XML no depèn d'una font externa (un arxiu d'schema DTD, XSD) xDeclaracio = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"); xmlDoc.InsertBefore(xDeclaracio, xmlDoc.DocumentElement); // afegim un comentari xComentari = xmlDoc.CreateComment("Usuaris"); xmlDoc.InsertAfter(xComentari, xDeclaracio); xNodeArrel = xmlDoc.CreateElement("Users"); xmlDoc.AppendChild(xNodeArrel); // afegim un comentari xComentari = xmlDoc.CreateComment("Fi de la llista"); xmlDoc.InsertAfter(xComentari, xNodeArrel); guardarXML(xmlDoc, nomFitxer); }
private void Init(string rootName) { try { doc = new XmlDocument(); var dec = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.InsertAfter(dec, null); root = doc.CreateNode(XmlNodeType.Element, rootName, ""); doc.InsertAfter(root, dec); } catch { } }
public static string UpdateProduct(string product, string buildNumber, string edition) { var prodDoc = new XmlDocument { XmlResolver = null }; prodDoc.Load(product); XmlProcessingInstruction lastOne = null; bool foundBuildNumber = false; bool foundEdition = false; Debug.Assert(prodDoc.DocumentElement != null, "prodDoc.DocumentElement != null"); foreach (var childNode in prodDoc.ChildNodes.Cast <XmlNode>().Where(childNode => childNode.NodeType == XmlNodeType.ProcessingInstruction).Cast <XmlProcessingInstruction>()) { if (childNode.Value.StartsWith("BUILD_NUMBER")) { childNode.Value = string.Format(@"BUILD_NUMBER=""{0}""", buildNumber); foundBuildNumber = true; } else if (childNode.Value.StartsWith("Edition")) { childNode.Value = string.Format(@"Edition=""{0}""", edition); foundEdition = true; } else { lastOne = childNode; } } if (!foundBuildNumber) { var verProcInst = prodDoc.CreateProcessingInstruction("define", string.Format(@"BUILD_NUMBER=""{0}""", buildNumber)); prodDoc.InsertAfter(verProcInst, lastOne); } if (!foundEdition) { var verProcInst = prodDoc.CreateProcessingInstruction("define", string.Format(@"Edition=""{0}""", edition)); prodDoc.InsertAfter(verProcInst, lastOne); } var tempName = Path.GetTempFileName(); var writer = XmlWriter.Create(tempName, new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 }); prodDoc.Save(writer); writer.Close(); return(tempName); }
public void CheckConfig() { if (!File.Exists(Path.Combine(ModuleFolder, "Config.xml"))) { Document = new XmlDocument(); XmlDeclaration declaration = Document.CreateXmlDeclaration("1.0", "utf-8", "yes"); XmlComment comment = Document.CreateComment("VPNBlocker Configuration"); Document.InsertBefore(declaration, Document.DocumentElement); Document.InsertAfter(comment, declaration); XmlElement element = Document.CreateElement("Configuration"); Document.AppendChild(element); XmlElement element2 = Document.CreateElement("bool"); element2.SetAttribute("iphub", iphub.ToString()); element.AppendChild(element2); XmlElement element3 = Document.CreateElement("string"); element3.SetAttribute("iphubkey", iphubkey); element.AppendChild(element3); Document.Save(Path.Combine(ModuleFolder, "Config.xml")); } else { iphub = Convert.ToBoolean(GetSetting("iphub")); iphubkey = GetSetting("iphubkey"); Logger.Log("iphubkey = " + iphubkey); } }
private void WriteResponseBody(IGraph graph, string mediaType, IResponseInfo response) { var writer = CreateWriter(mediaType); if (writer is RdfXmlWriter) { Stream buffer = new MemoryStream(); buffer = new UnclosableStream(buffer); using (var textWriter = new StreamWriter(buffer)) { writer.Save(graph, textWriter); } buffer.Seek(0, SeekOrigin.Begin); XmlDocument document = new XmlDocument(); document.Load(buffer); document.InsertAfter( document.CreateProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + DocumentationStylesheet + "\""), document.FirstChild); document.Save(response.Body); } else { using (var textWriter = new StreamWriter(response.Body)) { writer.Save(graph, textWriter); } } }
/// <summary> /// Add the DTD to the document and the root element. /// </summary> private void InitializeDatabase() { string elemList = ""; string attList = ""; foreach (string each in _tags) { elemList += "<!ELEMENT " + each + " ANY>"; attList += "<!ATTLIST " + each + " " + IdAttribute + " ID #REQUIRED>"; } XmlDocumentType dtd = _database.CreateDocumentType("db", null, null, elemList + attList); _database.InsertAfter(dtd, _database.FirstChild); if (_database.GetElementsByTagName("db").Count == 0) { XmlElement elem = _database.CreateElement("db"); _database.AppendChild(elem); } if (_createNewAction != null) { _createNewAction.BeginInvoke(null, null); } }
public static void Write() { XmlDocument optionsDocument = new XmlDocument(); XmlDeclaration xmlDecleration = optionsDocument.CreateXmlDeclaration("1.0", "UTF-8", null); optionsDocument.AppendChild(xmlDecleration); XmlNode optionsRoot = optionsDocument.CreateNode("element", "configuration", ""); optionsRoot.AppendChild(FillIn(optionsDocument)); optionsDocument.InsertAfter(optionsRoot, xmlDecleration); try { if (File.Exists(@"..\..\..\ConsoleXmlDiff\Configurations\XmlDiffOptions.config")) { File.Delete(@"..\..\..\ConsoleXmlDiff\Configurations\XmlDiffOptions.config"); } optionsDocument.Save(@"..\..\..\ConsoleXmlDiff\Configurations\XmlDiffOptions.config"); } catch (Exception ex) { throw ex; } }
/// <summary>序列化</summary> /// <param name="xsl">xsl文件</param> /// <returns></returns> public XmlDocument Serialize(String xsl) { var doc = new XmlDocument(); try { var ms = new MemoryStream(); //var xs = new XmlSerializer(this.GetType()); //xs.Serialize(ms, this); this.ToXml(ms, null, null, null, true); ms.Position = 0; doc.Load(ms); } catch { } if (!String.IsNullOrEmpty(xsl)) { //插入xsl文件引用 var xmlXsl = doc.CreateProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + xsl + "\""); doc.InsertAfter(xmlXsl, doc.ChildNodes[0]); } return(doc); }
private static string CreateInnerNoteContents(string[] checklist) { XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); XmlDocumentType xmlDoctype = doc.CreateDocumentType("en-note", null, "http://xml.evernote.com/pub/enml2.dtd", null); doc.InsertAfter(xmlDoctype, xmlDeclaration); XmlElement noteNode = doc.CreateElement("en-note"); doc.AppendChild(noteNode); foreach (var item in checklist) { XmlElement divNode = doc.CreateElement("div"); divNode.InnerText = item; XmlElement todoNode = doc.CreateElement("en-todo"); todoNode.SetAttribute("checked", "false"); divNode.AppendChild(todoNode); noteNode.AppendChild(divNode); } return(doc.InnerXml); }
/// <summary> /// Inspect an XML document. /// </summary> /// <param name="doc">The XML document to inspect.</param> private void InspectDocument(XmlDocument doc) { // inspect the declaration if (XmlNodeType.XmlDeclaration == doc.FirstChild.NodeType) { XmlDeclaration declaration = (XmlDeclaration)doc.FirstChild; if (!String.Equals("utf-8", declaration.Encoding, StringComparison.OrdinalIgnoreCase)) { if (this.OnError(InspectorTestType.DeclarationEncodingWrong, declaration, "The XML declaration encoding is not properly set to 'utf-8'.")) { declaration.Encoding = "utf-8"; } } } else // missing declaration { if (this.OnError(InspectorTestType.DeclarationMissing, null, "This file is missing an XML declaration on the first line.")) { XmlNode xmlDecl = doc.PrependChild(doc.CreateXmlDeclaration("1.0", "utf-8", null)); doc.InsertAfter(doc.CreateWhitespace("\r\n"), xmlDecl); } } // start inspecting the nodes at the document element this.InspectNode(doc.DocumentElement, 0); }
public XmlDocument OpenAppXMLFile() { string App_Path = @ConfigurationManager.AppSettings["Data_Path"].ToString(); App_Path = App_Path + "Items.xml"; if (File.Exists(@App_Path)) { try { xmldoc = new XmlDocument(); xmldoc.Load(@App_Path); } catch (Exception ex) { /// Do not currently understand how to terminate the ThreadStart in the event of a failure GlobalClass.ErrorMessage = "Error in AppThreads(OpenAppFile): " + ex.Message; } } else { xmldoc = new XmlDocument(); XmlNode iheader = xmldoc.CreateXmlDeclaration("1.0", "UTF-8", null); xmldoc.AppendChild(iheader); XmlElement root = xmldoc.CreateElement("dataroot"); xmldoc.InsertAfter(root, iheader); xmldoc.Save(@App_Path); } return xmldoc; }
// ---------------- Functions ---------------- public static XmlDocument ToXml(this LogBook logbook) { XmlDocument doc = new XmlDocument(); // Create declaration. XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null); // Add declaration to document. XmlElement?root = doc.DocumentElement; doc.InsertBefore(dec, root); XmlElement logbookNode = doc.CreateElement(XmlElementName); { XmlAttribute versionAttribute = doc.CreateAttribute(VersionAttributeName); versionAttribute.Value = XmlVersion.ToString(); logbookNode.Attributes.Append(versionAttribute); } List <Log> logList = logbook.ToList(); foreach (Log log in logList) { log.ToXml(doc, logbookNode); } doc.InsertAfter(logbookNode, dec); return(doc); }
public static void Store() { XmlDocument bindings = new XmlDocument(); XmlNode node; XmlElement element, child; XmlElement root = bindings.CreateElement("Controls"); bindings.InsertAfter(root, bindings.DocumentElement); for (int p = 0; p < 7; p++) { element = bindings.CreateElement("Player" + p); for (int i = 0; i < System.Enum.GetNames(typeof(UserInput)).Length; i++) { child = bindings.CreateElement("Keyboard_" + System.Enum.GetNames(typeof(UserInput))[i]); node = bindings.CreateTextNode("Keyboard_" + System.Enum.GetNames(typeof(UserInput))[i]); node.Value = keyBoard[i, p].ToString(); child.AppendChild(node); element.AppendChild(child); } for (int i = 0; i < System.Enum.GetNames(typeof(UserInput)).Length; i++) { child = bindings.CreateElement("Gamepad_" + System.Enum.GetNames(typeof(UserInput))[i]); node = bindings.CreateTextNode("Gamepad_" + System.Enum.GetNames(typeof(UserInput))[i]); node.Value = gamePad[i, p]; element.AppendChild(node); child.AppendChild(node); element.AppendChild(child); } root.AppendChild(element); } bindings.Save(filename); }
public void WriteXML() { StringWriter stringWriter = new StringWriter(); ds.WriteXml(new XmlTextWriter(stringWriter), XmlWriteMode.WriteSchema); string xmlStr = stringWriter.ToString(); XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlStr); XmlDeclaration xDeclare = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.InsertBefore(xDeclare, doc.FirstChild); // Create a procesing instruction. //XmlProcessingInstruction newPI; //String PItext = "<abc:stylesheet xmlns:abc=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">"; //String PItext = "type='text/xsl' href='book.xsl'"; string PItext = "html xsl:version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\""; XmlText newPI = doc.CreateTextNode(PItext); //newPI = docCreateProcessingInstruction("html", PItext); //newPI = doc.CreateComment(CreateDocumentType("html", PItext, "", ""); doc.InsertAfter(newPI, doc.FirstChild); doc.Save(xmlfilename); XslCompiledTransform myXslTrans = new XslCompiledTransform(); myXslTrans.Load(xmlfilename); string directoryPath = Path.GetDirectoryName(xmlfilename); myXslTrans.Transform(xmlfilename, directoryPath + "result.html"); webBrowser1.Navigate(directoryPath + "result.html"); }
/// <summary> /// Formats the provided XML so it's indented and humanly-readable. /// </summary> /// <param name="inputXml">The input XML to format.</param> /// <returns></returns> public static string FormatXml(XmlElement element) { XmlDocument document = new XmlDocument(); var node = document.ImportNode(element, true); document.InsertAfter(node, null); StringBuilder builder = new StringBuilder(); var xmlSettings = new XmlWriterSettings { Indent = true, IndentChars = @" ", NewLineChars = Environment.NewLine, NewLineHandling = NewLineHandling.Replace, OmitXmlDeclaration = true, Encoding = Encoding.UTF8, }; using (var writer = XmlWriter.Create(builder, xmlSettings)) { document.Save(writer); } return(builder.ToString()); }
public string WriteSVGString(bool compressAttributes) { string internalSubset = ""; XmlDocument xmlDocument = new XmlDocument(); XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", null, "yes"); xmlDocument.AppendChild(xmlDeclaration); this.WriteXmlElements(xmlDocument, null); xmlDocument.DocumentElement.SetAttribute("xmlns", "http://www.w3.org/2000/svg"); if (compressAttributes) { internalSubset = SvgFactory.CompressXML(xmlDocument, xmlDocument.DocumentElement); } xmlDocument.XmlResolver = new SvgElement.DummyXmlResolver(); xmlDocument.InsertAfter(xmlDocument.CreateDocumentType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", internalSubset), xmlDeclaration); MemoryStream memoryStream = new MemoryStream(); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding()); xmlTextWriter.Formatting = Formatting.None; xmlDocument.Save(xmlTextWriter); byte[] array = memoryStream.ToArray(); string @string = Encoding.UTF8.GetString(array, 0, array.Length); xmlTextWriter.Close(); return(@string); }
public static void SaveToXml(string fileName, List <Action> actionsList) { try { XmlDocument document = new XmlDocument(); XmlNode rootNode = document.CreateNode(XmlNodeType.Element, "Actions", ""); document.InsertAfter(rootNode, null); foreach (var action in actionsList) { var element = (XmlElement)action.WriteToXML(document); element.SetAttribute("Title", action.Name); rootNode.AppendChild(element); } document.Save(fileName); } catch (Exception ex) { Log.WriteLog(ex.Message, Color.Red); } }
public bool InsertXML(string grade, string classname, string typeName, string nodeName) { XmlDocument xmldoc = new XmlDocument(); string fileName = ""; if (grade == "高一年级") { fileName = "SENIONE.xml"; } else if (grade == "高二年级") { fileName = "SENITWO.xml"; } else if (grade == "高三年级") { fileName = "SENITHREE.xml"; } xmldoc.Load(@fileName); XmlNode rootNode = xmldoc.SelectSingleNode("grade"); XmlNode node1 = xmldoc.DocumentElement.SelectSingleNode("grade/class[@name = 'classname']/type"); XmlNode node2 = node1.Clone(); xmldoc.InsertAfter(node1, node2); xmldoc.Save(fileName); return(true); }
/// <summary> /// Get a string that contains a complete SVG document. XML version, DOCTYPE etc are included. /// </summary> /// <returns></returns> /// <param name="compressAttributes">Should usually be set true. Causes the XML output to be optimized so that /// long attributes like styles and transformations are represented with entities.</param> public string WriteSVGString(bool compressAttributes) { var doc = new XmlDocument(); var declaration = doc.CreateXmlDeclaration("1.0", null, "yes"); doc.AppendChild(declaration); //write out our SVG tree to the new XmlDocument WriteXmlElements(doc, null); doc.DocumentElement.SetAttribute("xmlns", "http://www.w3.org/2000/svg"); var ents = string.Empty; if (compressAttributes) { ents = SvgFactory.CompressXML(doc, doc.DocumentElement); } doc.XmlResolver = new DummyXmlResolver(); doc.InsertAfter( doc.CreateDocumentType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", ents), declaration ); return(ToXmlString(doc)); }
public Stream CreateExportedNote(DateTime date, string title, string[] checklist) { string formattedDate = date.ToString("yyyyMMddTHHmmssZ"); XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); XmlDocumentType xmlDoctype = doc.CreateDocumentType("en-export", null, "http://xml.evernote.com/pub/evernote-export2.dtd", null); doc.InsertAfter(xmlDoctype, xmlDeclaration); XmlElement enExportNode = doc.CreateElement("en-export"); enExportNode.SetAttribute("export-date", formattedDate); enExportNode.SetAttribute("application", "Evernote/MealPlanner"); enExportNode.SetAttribute("version", "6.x"); doc.AppendChild(enExportNode); XmlElement noteNode = doc.CreateElement("note"); enExportNode.AppendChild(noteNode); XmlElement titleNode = doc.CreateElement("title"); titleNode.InnerText = title; noteNode.AppendChild(titleNode); XmlElement contentNode = doc.CreateElement("content"); noteNode.AppendChild(contentNode); string innerNoteContents = CreateInnerNoteContents(checklist); XmlCDataSection cdata = doc.CreateCDataSection(innerNoteContents); contentNode.AppendChild(cdata); XmlElement createdNode = doc.CreateElement("created"); createdNode.InnerText = formattedDate; noteNode.AppendChild(createdNode); XmlElement updatedNode = doc.CreateElement("updated"); updatedNode.InnerText = formattedDate; noteNode.AppendChild(updatedNode); MemoryStream xmlStream = new MemoryStream(); doc.Save(xmlStream); xmlStream.Position = 0; return(xmlStream); }
public static void Write() { XmlDocument configDocument = new XmlDocument(); XmlDeclaration xmlDecleration = configDocument.CreateXmlDeclaration("1.0", "UTF-8", null); configDocument.AppendChild(xmlDecleration); XmlNode configRoot = configDocument.CreateNode("element", "configuration", ""); XmlNode configNode; configNode = configDocument.CreateNode("element", "NewToken", ""); configNode.InnerText = NewToken; configRoot.AppendChild(configNode); configNode = configDocument.CreateNode("element", "ReferenceToken", ""); configNode.InnerText = ReferenceToken; configRoot.AppendChild(configNode); configNode = configDocument.CreateNode("element", "DiffToken", ""); configNode.InnerText = DiffToken; configRoot.AppendChild(configNode); configNode = configDocument.CreateNode("element", "SummaryToken", ""); configNode.InnerText = SummaryToken; configRoot.AppendChild(configNode); configNode = configDocument.CreateNode("element", "MasterToken", ""); configNode.InnerText = MasterToken; configRoot.AppendChild(configNode); configNode = configDocument.CreateNode("element", "DiffFileName", ""); configNode.InnerText = DiffFileName; configRoot.AppendChild(configNode); configNode = configDocument.CreateNode("element", "DiffFileExtension", ""); configNode.InnerText = DiffFileExtension; configRoot.AppendChild(configNode); configNode = configDocument.CreateNode("element", "Separator", ""); configNode.InnerText = new string (Delimiter); configRoot.AppendChild(configNode); configDocument.InsertAfter(configRoot, xmlDecleration); try { if (File.Exists(@"..\..\..\ConsoleXmlDiff\Configurations\ApplicationConfiguration.config")) { File.Delete(@"..\..\..\ConsoleXmlDiff\Configurations\ApplicationConfiguration.config"); } configDocument.Save(@"..\..\..\ConsoleXmlDiff\Configurations\ApplicationConfiguration.config"); } catch (Exception ex) { MessageBox.Show(ex.Message); throw ex; } }
/// <summary> /// Writes RemoteInstall output to an XML file, also generates an XSL file in the same directory to use for XSLT /// </summary> public void Write(Results results, string fileName) { XmlDocument xml = results.GetXml(); string xslFileName = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + ".xsl"); XmlProcessingInstruction pi = xml.CreateProcessingInstruction("xml-stylesheet", string.Format("type=\"text/xsl\" href=\"{0}\"", Path.GetFileName(xslFileName))); xml.InsertAfter(pi, xml.FirstChild); xml.Save(fileName); Xsl.Save(xslFileName); }
public void CompileProgram(Program program) { currentElement = document.CreateElement("Program"); document.InsertAfter(currentElement, declaration); foreach (AstNode astNode in program.Statements) { astNode.AcceptCompiler(this); } }
public XmlNodeList GetAllEmrGroups() { if (docPattern == null) { return(null); } XmlNodeList groups = docPattern.DocumentElement.SelectNodes(ElementNames.Group); if (groups.Count == 1) { XmlElement group = docPattern.CreateElement(ElementNames.Group); group.SetAttribute(AttributeNames.Code, "2"); group.SetAttribute(AttributeNames.NoteID, "##"); group.SetAttribute(AttributeNames.NoteName, "护理记录"); XmlNode group2 = docPattern.DocumentElement.InsertAfter(group, groups.Item(0)); group = docPattern.CreateElement(ElementNames.Group); group.SetAttribute(AttributeNames.Code, "3"); group.SetAttribute(AttributeNames.NoteID, "##"); group.SetAttribute(AttributeNames.NoteName, "危重护理"); docPattern.InsertAfter(group, group2); putEmrPatternIntoDB(docPattern.DocumentElement); //emrPattern.Save(filePattern); } else if (groups.Count == 2) { XmlElement group = docPattern.CreateElement(ElementNames.Group); group.SetAttribute(AttributeNames.Code, "3"); group.SetAttribute(AttributeNames.NoteID, "##"); group.SetAttribute(AttributeNames.NoteName, "危重护理"); docPattern.DocumentElement.InsertAfter(group, groups.Item(1)); putEmrPatternIntoDB(docPattern); //docPattern.Save(filePattern); } foreach (XmlNode group in groups) { if (group.Attributes[AttributeNames.NoteName] == null) { string noteID = group.Attributes[AttributeNames.NoteID].Value; string noteName = GetNoteNameFromNoteID(noteID); XmlAttribute attr = group.OwnerDocument.CreateAttribute(AttributeNames.NoteName); attr.Value = noteName; group.Attributes.Append(attr); putEmrPatternIntoDB(docPattern.DocumentElement); // docPattern.Save(filePattern); } } return(docPattern.DocumentElement.SelectNodes(ElementNames.Group)); }
public string Serialize() { string xml; var qbxml = OnSerialize(); XmlWriterSettings xs = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = false, Encoding = Encoding.ASCII }; using (MemoryStream ms = new MemoryStream()) { using (var xw = XmlWriter.Create(ms, xs)) { var ser = new QBXMLSerializer(); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); ser.Serialize(xw, qbxml, ns); } ms.Position = 0; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(ms); XmlProcessingInstruction pi; pi = xmlDoc.CreateProcessingInstruction("qbxml", "version=\"13.0\""); xmlDoc.InsertAfter(pi, xmlDoc.FirstChild); using (MemoryStream ms2 = new MemoryStream()) { xmlDoc.Save(ms2); ms2.Position = 0; using (StreamReader sr = new StreamReader(ms2)) { xml = sr.ReadToEnd(); } } return(xml); } }
public void InsertNodeWithChild(string mainNode, string ChildNode, string Element, string Content) { XmlNodeList nodeList = XmlDoc.SelectSingleNode(mainNode).ChildNodes; foreach (XmlNode xn in nodeList) //遍历所有子节点 { XmlNodeList nls = xn.ChildNodes; //继续获取xe子节点的所有子节点 if (xn.Name == ChildNode) { XmlElement elem = XmlDoc.CreateElement("price"); elem.InnerText = "19.95"; //Add the node to the document. XmlDoc.InsertAfter(elem, xn.FirstChild); } } }
private void CreateRootNode(string psRootNodeTagName, string encoding, KeyValuePair <string, string>[] namespaces) { XmlDeclaration xmldec = _xmlDoc.CreateXmlDeclaration("1.0", encoding, null); XmlNode oRootNode = _xmlDoc.CreateElement(psRootNodeTagName); _xmlDoc.InsertAfter(oRootNode, null); _xmlDoc.InsertBefore(xmldec, oRootNode); if (namespaces != null) { if (namespaces.Length > 0) { for (int inx = 0; inx < namespaces.Length; inx++) { _xmlDoc.DocumentElement.SetAttribute(namespaces[inx].Key, namespaces[inx].Value); } } } }
// ---------------- Functions ---------------- public string ToXml() { XmlDocument doc = new XmlDocument(); // Create declaration. XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null); // Add declaration to document. XmlElement root = doc.DocumentElement; doc.InsertBefore(dec, root); // Root Node XmlElement rootNode = doc.CreateElement("chaskis_http_response"); // Create Response Status node { XmlElement statusNode = doc.CreateElement("status"); statusNode.InnerText = this.ResponseStatus.ToString(); rootNode.AppendChild(statusNode); } { XmlElement errorMsg = doc.CreateElement("error_message"); errorMsg.InnerText = this.Error.ToString(); rootNode.AppendChild(errorMsg); } // Create Message Node { XmlElement messageNode = doc.CreateElement("message"); messageNode.InnerText = this.Message ?? string.Empty; rootNode.AppendChild(messageNode); } doc.InsertAfter(rootNode, dec); using (StringWriter stringWriter = new StringWriter()) { doc.Save(stringWriter); return(stringWriter.GetStringBuilder().ToString()); } }
/// <summary> /// Get a string that contains a complete SVG document. XML version, DOCTYPE etc are included. /// </summary> /// <returns></returns> /// <param name="compressAttributes">Should usually be set true. Causes the XML output to be optimized so that /// long attributes like styles and transformations are represented with entities.</param> public string WriteSVGString(bool compressAttributes) { string s; string ents = ""; XmlDocument doc = new XmlDocument(); var declaration = doc.CreateXmlDeclaration("1.0", null, "yes"); doc.AppendChild(declaration); //write out our SVG tree to the new XmlDocument WriteXmlElements(doc, null); doc.DocumentElement.SetAttribute("xmlns", "http://www.w3.org/2000/svg"); if (compressAttributes) { ents = SvgFactory.CompressXML(doc, doc.DocumentElement); } doc.XmlResolver = new DummyXmlResolver(); doc.InsertAfter( doc.CreateDocumentType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", ents), declaration ); //This complicated business of writing to a memory stream and then reading back out to a string //is necessary in order to specify UTF8 -- for some reason the default is UTF16 (which makes most renderers //give up) MemoryStream ms = new MemoryStream(); XmlTextWriter wr = new XmlTextWriter(ms, new UTF8Encoding()); wr.Formatting = Formatting.None; // Indented formatting would be nice for debugging but causes unwanted trailing white spaces between <text> and <tspan> elements in Internet Explorer doc.Save(wr); byte[] buf = ms.ToArray(); s = Encoding.UTF8.GetString(buf, 0, buf.Length); wr.Close(); return(s); }
protected static void ReGenerateSchema(XmlDocument xmlDoc) { string dtd = DocumentType.GenerateXmlDocumentType(); // remove current doctype XmlNode n = xmlDoc.FirstChild; while (n.NodeType != XmlNodeType.DocumentType && n.NextSibling != null) { n = n.NextSibling; } if (n.NodeType == XmlNodeType.DocumentType) { xmlDoc.RemoveChild(n); } XmlDocumentType docType = xmlDoc.CreateDocumentType("root", null, null, dtd); xmlDoc.InsertAfter(docType, xmlDoc.FirstChild); }
// Test adding an XML declaration to the document. public void TestXmlDocumentAddXmlDeclaration() { XmlDocument doc = new XmlDocument(); // Add the declaration. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null); AssertNull("XmlDeclaration (1)", decl.ParentNode); AssertEquals("XmlDeclaration (2)", doc, decl.OwnerDocument); doc.AppendChild(decl); AssertEquals("XmlDeclaration (3)", doc, decl.ParentNode); AssertEquals("XmlDeclaration (4)", doc, decl.OwnerDocument); // Try to add it again, which should fail this time. try { doc.AppendChild(decl); Fail("adding XmlDeclaration node twice"); } catch(InvalidOperationException) { // Success } try { doc.PrependChild(decl); Fail("prepending XmlDeclaration node twice"); } catch(InvalidOperationException) { // Success } // Adding a document type before should fail. XmlDocumentType type = doc.CreateDocumentType("foo", null, null, null); try { doc.PrependChild(type); Fail("prepending XmlDocumentType"); } catch(InvalidOperationException) { // Success } // Adding a document type after should succeed. doc.AppendChild(type); // Adding an element before should fail. XmlElement element = doc.CreateElement("foo"); try { doc.PrependChild(element); Fail("prepending XmlElement"); } catch(InvalidOperationException) { // Success } // Adding the element between decl and type should fail. try { doc.InsertAfter(element, decl); Fail("inserting XmlElement between XmlDeclaration " + "and XmlDocumentType"); } catch(InvalidOperationException) { // Success } try { doc.InsertBefore(element, type); Fail("inserting XmlElement between XmlDeclaration " + "and XmlDocumentType (2)"); } catch(InvalidOperationException) { // Success } // Adding an element after should succeed. doc.AppendChild(element); }