public static void NameOfAllTypes() { var xmlDocument = new XmlDocument(); var element = xmlDocument.CreateElement("newElem"); Assert.Equal("newElem", element.Name); var attribute = xmlDocument.CreateAttribute("newAttr"); Assert.Equal("newAttr", attribute.Name); var text = xmlDocument.CreateTextNode(""); Assert.Equal("#text", text.Name); var cdata = xmlDocument.CreateCDataSection(""); Assert.Equal("#cdata-section", cdata.Name); var pi = xmlDocument.CreateProcessingInstruction("PI", ""); Assert.Equal("PI", pi.Name); var comment = xmlDocument.CreateComment("some text"); Assert.Equal("#comment", comment.Name); var fragment = xmlDocument.CreateDocumentFragment(); Assert.Equal("#document-fragment", fragment.Name); }
public static void SubstringBeforeBeginning() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("abcde"); Assert.Throws<ArgumentOutOfRangeException>(() => cdataNode.Substring(-1, 1)); }
public static void CreateCdata() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("abcde"); Assert.Equal(5, cdataNode.Length); }
public static void CreateEmptyCdata() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection(String.Empty); Assert.Equal(0, cdataNode.Length); }
public static void InsertDataBeyondEndOfCdataNodeBigNumber() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("hello"); Assert.Throws<ArgumentOutOfRangeException>(() => cdataNode.InsertData(10, "hello ")); }
public static void LengthOfCdataAfterDelete() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("abcde"); cdataNode.DeleteData(0, 1); Assert.Equal(4, cdataNode.Length); }
public static void InsertCDataNodeToDocumentNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<a/>"); var cDataSection = xmlDocument.CreateCDataSection("data"); Assert.Throws<InvalidOperationException>(() => xmlDocument.InsertBefore(cDataSection, null)); }
public static void Replace4CharactersFromCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("abcde"); cdataNode.ReplaceData(1, 4, "test"); Assert.Equal("atest", cdataNode.Data); }
public static void Replace1CharactersFromCdataNodeBeginning() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("abcde"); cdataNode.ReplaceData(0, 1, "&"); Assert.Equal("&bcde", cdataNode.Data); }
public static void ReplaceAllCharactersFromCdataNodeBeginning() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("abcdefgh"); cdataNode.ReplaceData(0, cdataNode.Length, "new string"); Assert.Equal("new string", cdataNode.Data); }
public static void CDataNodeNode() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateCDataSection("cdata section"); Assert.Equal("cdata section", node.Value); node.Value = "new cdata"; Assert.Equal("new cdata", node.Value); }
public static void EmptyString() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection(String.Empty); var subString = cdataNode.Substring(0, 10); Assert.Equal(String.Empty, subString); }
public static void InsertDataAtMiddleOfCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("comment"); cdataNode.InsertData(3, " hello "); Assert.Equal("com hello ment", cdataNode.Data); }
public static void InsertDataInEmptyCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection(null); cdataNode.InsertData(0, "hello"); Assert.Equal("hello", cdataNode.Data); }
public static void ReplaceCharactersFromCdataNodeWhenStringIsShorter() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("abcdefgh"); var newString = "new string"; cdataNode.ReplaceData(0, newString.Length + 1, newString); Assert.Equal(newString, cdataNode.Data); }
public static void CreateCDataTest4() { var xmlDocument = new XmlDocument(); var cdata = xmlDocument.CreateCDataSection("=\"&<> : ;; @#$%^&*()\"~\"' "); Assert.Equal("<![CDATA[=\"&<> : ;; @#$%^&*()\"~\"' ]]>", cdata.OuterXml); Assert.Equal(String.Empty, cdata.InnerXml); Assert.Equal("=\"&<> : ;; @#$%^&*()\"~\"' ", cdata.InnerText); Assert.Equal(XmlNodeType.CDATA, cdata.NodeType); }
public static void CreateCDataTest2() { var xmlDocument = new XmlDocument(); var cdata = xmlDocument.CreateCDataSection("test data"); Assert.Equal("<![CDATA[test data]]>", cdata.OuterXml); Assert.Equal(String.Empty, cdata.InnerXml); Assert.Equal("test data", cdata.InnerText); Assert.Equal(XmlNodeType.CDATA, cdata.NodeType); }
public static void CreateCDataTest3() { var xmlDocument = new XmlDocument(); var cdata = xmlDocument.CreateCDataSection("]]>"); Assert.Throws<ArgumentException>(() => { var test = cdata.OuterXml; }); Assert.Equal(String.Empty, cdata.InnerXml); Assert.Equal("]]>", cdata.InnerText); Assert.Equal(XmlNodeType.CDATA, cdata.NodeType); }
public static void SubstringLongerThanData() { var xmlDocument = new XmlDocument(); var testString = "abcde"; var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection(testString); var subString = cdataNode.Substring(0, testString.Length + 2); Assert.Equal(testString, subString); }
public static void Substring() { var xmlDocument = new XmlDocument(); var testString = "abcde"; var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection(testString); var subString = cdataNode.Substring(0, 2); Assert.Equal("ab", subString); }
public static void CreateCDataTest5() { var xmlDocument = new XmlDocument(); var text = "X X"; var cdata = xmlDocument.CreateCDataSection(text); Assert.Equal("<![CDATA[" + text + "]]>", cdata.OuterXml); Assert.Equal(String.Empty, cdata.InnerXml); Assert.Equal(text, cdata.InnerText); Assert.Equal(XmlNodeType.CDATA, cdata.NodeType); }
/// <summary> /// 添加XmlCData结点,与上面完全一样,真是另类重载呀 /// </summary> /// <param name="doc">XmlDocument</param> /// <param name="e">parent node</param> /// <param name="NodeName">append node</param> /// <param name="NodeValue">append node text</param> public XmlElement AddXmlCDataNode(XmlDocument doc, XmlElement e, string NodeName, string NodeValue) { //对XML文档添加XML元素 XmlElement tempXmlElement = doc.CreateElement(NodeName); //添加结点文本 XmlCDataSection tempXmlText = doc.CreateCDataSection(NodeValue); //添加结点文本元素当中 tempXmlElement.AppendChild(tempXmlText); //在指定结点添加结点信息 e.AppendChild(tempXmlElement); return(tempXmlElement); }
/// <summary> /// 创建XmlCDataSection /// </summary> /// <param name="xdoc">所属XmlDocument</param> /// <param name="nodeName">节点名称</param> /// <param name="value">值</param> /// <returns>XmlCDataSection</returns> public static XmlCDataSection CreateXmlCDataSection(XmlDocument xdoc, string nodeName, string value) { if (string.IsNullOrWhiteSpace(nodeName)) { throw new ArgumentNullException(nameof(nodeName)); } XmlCDataSection node = xdoc.CreateCDataSection(nodeName); if (value != null) { node.InnerText = value; } return(node); }
internal void AppendValue(string containerName, string value) { _evnt.WaitOne(); XmlElement elem = _FindContainer(containerName); if (elem.ChildNodes.Count > 0) { value = ((XmlCDataSection)elem.ChildNodes[0]).Data + value; elem.RemoveChild(elem.ChildNodes[0]); } XmlCDataSection cda = _doc.CreateCDataSection(value); elem.AppendChild(cda); _evnt.Set(); }
public override void CreateElement() { var xmlPage = Doc.CreateElement(string.Empty, "page", string.Empty); foreach (var attributeKeyPair in Attributes) { xmlPage.Attributes.Append(attributeKeyPair.Value); } if (!string.IsNullOrEmpty(_content)) { var cdata = _doc.CreateCDataSection(_content); xmlPage.AppendChild(cdata); } Parent.AppendChild(xmlPage); base.CreateElement(); }
private XmlNode GetStubResult() { var doc = new XmlDocument(); var test = doc.CreateElement("test-run"); test.AddAttribute("start-time", DateTime.UtcNow.ToString("u")); doc.AppendChild(test); #if !NETSTANDARD1_6 var cmd = doc.CreateElement("command-line"); var cdata = doc.CreateCDataSection(Environment.CommandLine); cmd.AppendChild(cdata); test.AppendChild(cmd); #endif return(doc); }
/// <summary> /// Creates a cdata XmlNode with the specified name and value /// </summary> /// <param name="xd">The xmldocument.</param> /// <param name="name">The node name.</param> /// <param name="value">The node value.</param> /// <returns>A XmlNode</returns> public static XmlNode AddCDataNode(XmlDocument xd, string name, string value) { if (xd == null) { throw new ArgumentNullException("xd"); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullOrEmptyException(nameof(name)); } var temp = xd.CreateNode(XmlNodeType.Element, name, ""); temp.AppendChild(xd.CreateCDataSection(value)); return(temp); }
internal static void MergeFileIntoCData(XmlDocument doc, string codeFile, string xPathExpr) { var node = doc.SelectSingleNode(xPathExpr); if (node == null) { throw new ArgumentException("xPathExpr", $"No node found matching {xPathExpr}."); } Console.WriteLine($" Merging {codeFile}"); var contents = File.ReadAllText(codeFile, Encoding.UTF8); var cdata = doc.CreateCDataSection(contents); node.InnerXml = cdata.OuterXml; }
///<param name="xmlPath">file path</param> ///<param name="MailNode">current node</param> ///<param name="ChildNode">new node</param> ///<param name="Element">child node for new node</param> ///<param name="Content">child node content</param> public static void XmlInsertNode(string xmlPath, string MailNode, string ChildNode, string Element, string Content) { XmlDocument doc = new XmlDocument(); doc.Load(xmlPath); XmlNode objrootNode = doc.SelectSingleNode(MailNode); XmlElement objchildNode = doc.CreateElement(ChildNode); objrootNode.AppendChild(objchildNode); XmlElement objElement = doc.CreateElement(Element); XmlCDataSection xcds = doc.CreateCDataSection(Content); objElement.AppendChild(xcds); objchildNode.AppendChild(objElement); doc.Save(xmlPath); }
private XmlNode CreateANewFailureNode(XmlDocument xmlDoc) { XmlNode failureNode = xmlDoc.CreateNode(XmlNodeType.Element, NodeNames.failure.String(), ""); XmlNode messageNode = xmlDoc.CreateNode(XmlNodeType.Element, NodeNames.message.String(), ""); XmlCDataSection cdata = xmlDoc.CreateCDataSection("One or more child tests had errors"); messageNode.AppendChild(cdata); XmlNode stackTraceNode = xmlDoc.CreateNode(XmlNodeType.Element, NodeNames.stackTrace.String(), ""); failureNode.AppendChild(messageNode); failureNode.AppendChild(stackTraceNode); return(failureNode); }
public void SetMessage(string msg, int typeID) { XmlDocument xmlFile = GetResourceXmlFile(filePath); XmlNodeList nodes = xmlFile.DocumentElement.SelectSingleNode("messages").ChildNodes; foreach (XmlNode node in nodes) { if (node.SelectSingleNode("current").InnerText.Trim().Equals("true")) { node.SelectSingleNode("current").InnerText = "false"; } } XmlElement msgElem = xmlFile.CreateElement("message"); //add current node to message node XmlElement msgCurrentNode = xmlFile.CreateElement("current"); XmlText trueMsgNode = xmlFile.CreateTextNode("true"); msgCurrentNode.AppendChild(trueMsgNode); msgElem.AppendChild(msgCurrentNode); xmlFile.DocumentElement.AppendChild(msgElem); //add text node to message node XmlElement messageTextNode = xmlFile.CreateElement("text"); //XmlText xmlMsg = xmlFile.CreateTextNode(msg.Trim()); //messageTextNode.AppendChild(xmlMsg); msg = msg.Replace("\r\n", "<br />"); var cdata = xmlFile.CreateCDataSection(msg.Trim()); messageTextNode.AppendChild(cdata); msgElem.AppendChild(messageTextNode); xmlFile.DocumentElement.AppendChild(msgElem); //add type node to message node XmlElement messageTypeNode = xmlFile.CreateElement("msgType"); XmlText xmlmsgType = xmlFile.CreateTextNode(typeID.ToString()); messageTypeNode.AppendChild(xmlmsgType); msgElem.AppendChild(messageTypeNode); xmlFile.DocumentElement.SelectSingleNode("messages").AppendChild(msgElem); xmlFile.Save(filePath); }
private void Invoke_Click(object sender, HtmlElementEventArgs e) { bool argumentParsingFailed = false; XmlElement[] parameters = verb.Arguments.Select(argument => { try { return(GetValue(argument)); } catch (Exception ex) { MessageBox.Show( $"Error while parsing argument {argument.Name}, invocation won't happen:\n\n{ex.Message}", ex.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Error); argumentParsingFailed = true; return(null); } }).ToArray(); if (argumentParsingFailed) { return; } var doc = new XmlDocument(); try { XmlElement result = ConnectionInfo.Proxy.Invoke(verb.EntityName, verb.Name, parameters); doc.AppendChild(doc.ImportNode(result, true)); } catch (FaultException ex) { using (XmlWriter appendChild = doc.CreateNavigator().AppendChild()) ex.CreateMessageFault().WriteTo(appendChild, EnvelopeVersion.Soap12); } catch (Exception ex) { doc.AppendChild(doc.CreateElement("exception")); doc.DocumentElement.AppendChild(doc.CreateCDataSection(ex.ToString())); } xmlBrowser1.XmlDocument = doc; }
public void SerializeNodeTypes() { XmlDocument doc = new XmlDocument(); string jsonText; Console.WriteLine("SerializeNodeTypes"); // XmlAttribute XmlAttribute attribute = doc.CreateAttribute("msdata:IsDataSet"); attribute.Value = "true"; jsonText = JavaScriptConvert.SerializeXmlNode(attribute); Console.WriteLine(jsonText); Assert.AreEqual(@"{""@msdata:IsDataSet"":""true""}", jsonText); // XmlProcessingInstruction XmlProcessingInstruction instruction = doc.CreateProcessingInstruction("xml-stylesheet", @"href=""classic.xsl"" type=""text/xml"""); jsonText = JavaScriptConvert.SerializeXmlNode(instruction); Console.WriteLine(jsonText); Assert.AreEqual(@"{""?xml-stylesheet"":""href=\""classic.xsl\"" type=\""text/xml\""""}", jsonText); // XmlProcessingInstruction XmlCDataSection cDataSection = doc.CreateCDataSection("<Kiwi>true</Kiwi>"); jsonText = JavaScriptConvert.SerializeXmlNode(cDataSection); Console.WriteLine(jsonText); Assert.AreEqual(@"{""#cdata-section"":""<Kiwi>true</Kiwi>""}", jsonText); // XmlElement XmlElement element = doc.CreateElement("xs:Choice"); element.SetAttributeNode(attribute); element.AppendChild(instruction); element.AppendChild(cDataSection); jsonText = JavaScriptConvert.SerializeXmlNode(element); Console.WriteLine(jsonText); Assert.AreEqual(@"{""xs:Choice"":{""@msdata:IsDataSet"":""true"",""?xml-stylesheet"":""href=\""classic.xsl\"" type=\""text/xml\"""",""#cdata-section"":""<Kiwi>true</Kiwi>""}}", jsonText); }
/// <summary> /// Обработать узлы со свойствами. /// </summary> /// <param name="componentPath">Путь компоненты.</param> /// <param name="nodes">Узел со свойствами.</param> private void ImportPropertyNodes(string componentPath, XmlNodeList nodes) { var eventsPath = Path.Combine(componentPath, EventsFolder); var encoding = TransformerEnvironment.CurrentEncoding; foreach (XmlElement element in nodes) { var propertyName = element.GetAttribute("Name"); if (this.eventFileNamesBlocks.ContainsKey(propertyName) && Directory.Exists(eventsPath)) { var eventTextNode = element.SelectSingleNode("Value/Value"); var eventFilePath = Path.Combine(eventsPath, this.eventFileNamesBlocks[propertyName]); if (eventTextNode == null || !File.Exists(eventFilePath)) { continue; } var bytes = File.ReadAllBytes(eventFilePath); var encodedActionText = string.Format("{0}{1}", MimeCodedTextGuid, Convert.ToBase64String(bytes)); XmlDocument doc = eventTextNode.OwnerDocument; var cData = doc.CreateCDataSection(encodedActionText); eventTextNode.AppendChild(cData); } else { var valueNodes = element.SelectNodes("Value/Value"); if (valueNodes == null) { continue; } foreach (XmlElement valueNode in valueNodes) { var valueTextNode = valueNode.SelectSingleNode("text()"); if (valueTextNode == null || string.IsNullOrEmpty(valueTextNode.Value)) { continue; } var valueText = valueTextNode.Value; var encodedActionText = string.Format("{0}{1}", MimeCodedTextGuid, Convert.ToBase64String(encoding.GetBytes(valueText))); valueTextNode.Value = encodedActionText; } } } }
/// <summary> /// 设置节点的值 /// </summary> /// <param name="itemsEle">当前元素的父级元素</param> /// <param name="name">当前元素名称</param> /// <param name="value">元素的值</param> static void SetNodeValue(XmlElement itemsEle, string name, string value) { string nodeName = name.Trim(); XmlNode node = itemsEle.SelectSingleNode(string.Format("subItem[@name='{0}']", nodeName)); if (node == null) { XmlElement newElement = _softOptionXml.CreateElement("subItem"); newElement.SetAttribute("name", nodeName); itemsEle.AppendChild(newElement); node = (XmlNode)newElement; } node.InnerText = ""; XmlCDataSection data = _softOptionXml.CreateCDataSection(value); node.AppendChild(data); }
/// <summary> /// Update a selected placemarker /// </summary> /// <param name="town"></param> public void Update(Placemark town) { var KmlFile = XDocument.Load(_filename); XNamespace KmlNamespace = "http://www.opengis.net/kml/2.2"; // find the Placemarks in the Photos folder IEnumerable <XElement> Placemarks = KmlFile.Element(KmlNamespace + "kml").Element(KmlNamespace + "Document").Element(KmlNamespace + "Folder").Elements(KmlNamespace + "Placemark"); foreach (XElement p in Placemarks) { XmlDocument doc = new XmlDocument(); var value = String.Format("{0}<br>Revenue:{1}", p.Element(KmlNamespace + "description").Value, 100); p.Element(KmlNamespace + "description").Value = doc.CreateCDataSection(value).OuterXml; } KmlFile.Save(@"C:\Development\KML\KML.UnitTests\update.kml"); }
/// <summary> /// 添加节点 /// </summary> /// <param name="parentNode"></param> /// <param name="title"></param> /// <param name="value"></param> /// <param name="isCData"></param> public static void AddNode(XmlDocument xmlDoc, XmlNode parentNode, string title, string value, bool isCData) { XmlElement ele = xmlDoc.CreateElement(title); //是否要添加cdata if (isCData) { XmlCDataSection xcs = xmlDoc.CreateCDataSection(title); xcs.InnerText = value; ele.AppendChild(xcs); } else { ele.InnerText = value; } parentNode.AppendChild(ele); }
static void Main(string[] args) { StreamReader sr = File.OpenText("Entries.txt"); XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDec1 = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); xmlDoc.AppendChild(xmlDec1); XmlElement entriesElement = xmlDoc.CreateElement("entries"); while (!sr.EndOfStream) { string line = sr.ReadLine(); string[] fields = line.Split('|'); XmlElement entryElement = xmlDoc.CreateElement("entry"); entryElement.SetAttribute("type", fields[0]); XmlElement amountElement = xmlDoc.CreateElement("amount"); amountElement.InnerText = fields[1]; XmlElement dateElement = xmlDoc.CreateElement("date"); dateElement.InnerText = fields[2]; XmlElement descriptionElement = xmlDoc.CreateElement("description"); XmlCDataSection cDadaDescription = xmlDoc.CreateCDataSection(fields[3]); descriptionElement.AppendChild(cDadaDescription); XmlElement categoryElement = xmlDoc.CreateElement("category"); categoryElement.InnerText = fields[4]; entryElement.AppendChild(amountElement); entryElement.AppendChild(dateElement); entryElement.AppendChild(descriptionElement); entryElement.AppendChild(categoryElement); entriesElement.AppendChild(entryElement); } xmlDoc.AppendChild(entriesElement); xmlDoc.Save("Entries.xml"); sr.Close(); }
public XmlNode WriteToXmlNode() { XmlDocument doc = new XmlDocument(); XmlElement toNode = doc.CreateElement("timeout_setting"); toNode.SetAttribute("action", m_action); toNode.SetAttribute("linkTimerID", Convert.ToString(m_timerMissionID)); //1. 构建具体时间节点 if (m_ExactTime != null) { XmlElement et = doc.CreateElement("exact_time"); et.InnerText = m_ExactTime.Value.ToString(); toNode.AppendChild(et); } //2. 构建偏移时间节点 if (m_startTime != null && m_timeOffset != null) { XmlElement ot = doc.CreateElement("offset_time"); string time_start = ""; switch (m_startTime) { case TIME_START.TIME_WF_CREATE: time_start = "wf_create"; break; case TIME_START.TIME_EVENT_ENTER: time_start = "ev_enter"; break; } ot.SetAttribute("time_start", time_start); ot.SetAttribute("time_offset", m_timeOffset.Value.ToString()); toNode.AppendChild(ot); } //3. 构建callback节点 XmlElement cb = doc.CreateElement("call_back"); cb.AppendChild(doc.CreateCDataSection(CallbackUrl)); toNode.AppendChild(cb); return(toNode); }
/// <summary> /// 写入 value 到 CData /// </summary> /// <param name="key"></param> /// <param name="strValue"></param> /// <param name="xmlFileName"></param> /// <param name="nIndex">CDATA 在 childnode 中 的索引</param> /// <returns></returns> public static string WriteCData_inAppSettingsLikeXML(string key, string strValue, string xmlFileName, int nIndex = 0) { string Error_Msg = ""; xmlFileName = AvoidXmlNotFound_DuringDebug(xmlFileName); XmlDocument doc = new XmlDocument(); try { doc.Load(xmlFileName); //加载 Xml 文件 XmlElement rootElem = doc.DocumentElement; //获取根节点 XmlElement node = null; foreach (var xmlNode in rootElem.ChildNodes) { node = xmlNode as XmlElement; if (node == null) { continue; } if (node.NodeType == XmlNodeType.Element && node.GetAttribute("key").Trim() == key.Trim()) { if (node.ChildNodes.Count > nIndex && node.ChildNodes[nIndex] != null && node.ChildNodes[nIndex].NodeType == XmlNodeType.CDATA) { node.ChildNodes[nIndex].Value = strValue; } else // 若不存在则新增 Cdata { XmlCDataSection m_cdata = doc.CreateCDataSection(strValue); node.AppendChild(m_cdata); } doc.Save(xmlFileName); } } } catch (Exception ex) { SimpleLogHelper.Error(ex); return(ex.Message); } return(Error_Msg); }
/// <summary> /// 创建XML节点元素 /// </summary> /// <param name="xmlDoc">文档</param> /// <param name="eleName">元素名称</param> /// <param name="eleValue">元素值</param> /// <param name="useCData">是否使用CDATA</param> /// <returns></returns> private XmlElement createXmlElement(XmlDocument xmlDoc, string eleName, object eleValue, bool useCData = false) { var xmlNode = xmlDoc.CreateElement(eleName); var eleVal = string.Format("{0}", eleValue); if (useCData) { xmlNode.AppendChild(xmlDoc.CreateCDataSection(eleVal)); } else { xmlNode.AppendChild(xmlDoc.CreateTextNode(eleVal)); } return(xmlNode); }
public static XmlElement CreateXmlNodeCDATA(XmlDocument xDocument, string elementName, string cdataValue) { XmlElement result; try { XmlElement xmlElement = xDocument.CreateElement(elementName); XmlCDataSection newChild = xDocument.CreateCDataSection(cdataValue); xmlElement.AppendChild(newChild); result = xmlElement; } catch (Exception ex) { throw ex; } return(result); }
/// <summary> /// Binds the RSS news. /// </summary> private void BindRssNews() { string ss = ""; if (!String.IsNullOrEmpty(RssPath)) { RssDocument rssDocument = null; try { rssDocument = RssDocument.Load(new Uri(RssPath)); } catch { Response.ContentType = "text/xml"; Response.Write("<div style='text-align:center;padding:10px;color:red;' class='text'>" + RM.GetString("RSS_ERROR") + "</div>"); return; } // Create root element XmlDocument doc = new XmlDocument(); XmlNode root = doc.AppendChild(doc.CreateElement("rssData")); XmlNode node = doc.CreateElement("htmlData"); RssChannel channel = rssDocument.Channel; StringBuilder sb = new StringBuilder(); sb.AppendFormat("<div>"); sb.AppendFormat("<div style='padding-top: 3px;padding-bottom:3px;color: #444;font-size: 10pt;'><b>{0}</b></div>", channel.Title); for (int i = 0; i < channel.Items.Count && i < RssCount; i++) { sb.AppendFormat("<div style='padding-top: 3px;' class='text'><a href='{1}' target='_blank'>{0}</a></div>", channel.Items[i].Title, channel.Items[i].Link); sb.AppendFormat("<div style='color: gray;' class='text'>{0}</div>", channel.Items[i].PubDate); //sb.AppendFormat("<div style='color: black; font-family: tahoma; font-size: 12px;'>{0}</div>", channel.Items[i].Attributes["description"]); } sb.Append("</div>"); XmlNode cdata = doc.CreateCDataSection(sb.ToString()); //node.Name = "htmlData"; node.AppendChild(cdata); root.AppendChild(node); //doc.DocumentElement.AppendChild(doc.CreateCDataSection(sb.ToString())); ss += doc.InnerText; } Response.ContentType = "text/xml"; Response.Write(ss); }
/// <summary> /// 创建XML 数据文件 News the XML. /// </summary> /// <returns></returns> public bool NewXml(int ID) { try { XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", ROYcms.Config.ROYcmsConfig.GetCmsConfigValue("templet_language"), null); doc.AppendChild(dec); //创建一个根节点(一级) XmlElement root = doc.CreateElement("ROYcms"); doc.AppendChild(root); //创建节点(二级) XmlNode node = doc.CreateElement("Order"); XmlAttribute attr = null; attr = doc.CreateAttribute("Time"); attr.Value = DateTime.Now.ToString(); node.Attributes.SetNamedItem(attr); for (int i = 0; i < Request.Form.Count; i++) { //Request.Form.Remove(""); //带有"<![CDATA[ ]]>"的元素 if (!Request.Form.GetKey(i).Contains("_")) { XmlElement element = doc.CreateElement(Request.Form.GetKey(i)); //element.SetAttribute("Name", Request.Form.GetKey(i)); ////element.InnerText = "Round Comment"; XmlCDataSection idata = doc.CreateCDataSection("item"); idata.InnerText = Request.Form.Get(i); element.AppendChild(idata); node.AppendChild(element); } } root.AppendChild(node); if (!Directory.Exists(Server.MapPath("~/APP_XML/Order/"))) { Directory.CreateDirectory(Server.MapPath("~/APP_XML/Order/")); //创建新路径 } doc.Save(Server.MapPath("~/APP_XML/Order/" + ID + ".xml")); Console.Write(doc.OuterXml); return(true); } catch { return(false); } }
private static XmlElement GenerateNameAndValueForParent(XmlDocument document, string parentElementName, string nameText, string valText = " ") { var parentElement = document.CreateElement(parentElementName); var nameElement = document.CreateElement("name"); nameElement.InnerText = nameText; var valElement = document.CreateElement("val"); valElement.AppendChild(document.CreateCDataSection($"<p style=\"\">{valText}</p>")); parentElement.AppendChild(nameElement); parentElement.AppendChild(valElement); return(parentElement); }
private void fixSourceCodeNode(Stream inputStream, Stream outputStream) { inputStream.Seek(0, SeekOrigin.Begin); XmlDocument xml = new XmlDocument(); xml.Load(inputStream); List <XmlNode> SourceCodeNodes = new List <XmlNode>(); findSourceCodeNodes(SourceCodeNodes, xml.DocumentElement); foreach (XmlNode SourceCodeNode in SourceCodeNodes) { XmlNode newNode = xml.CreateCDataSection(SourceCodeNode.ChildNodes[0].Value); SourceCodeNode.RemoveAll(); SourceCodeNode.AppendChild(newNode); } xml.Save(outputStream); }
public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Create a CData section. XmlCDataSection CData; CData = doc.CreateCDataSection("All\r\n Jane\r\n Austen novels 25% off starting 3/23!"); //Add the new node to the document. XmlElement root = doc.DocumentElement; root.AppendChild(CData); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); }
public static void AppendCData(XmlNode node, string tag, string content) { if (String.IsNullOrEmpty(content) == true) { return; } XmlDocument doc = node.OwnerDocument; if (node is XmlDocument) { doc = (XmlDocument)node; } XmlElement element = (XmlElement)node.AppendChild(doc.CreateElement(tag)); element.AppendChild(doc.CreateCDataSection(content)); }
/// <summary> /// 插入子节点(将内容以CData形式写入) /// </summary> /// <param name="parentNode">要插入的父节点</param> /// <param name="elementName">插入的节点名称</param> /// <param name="elementContent">节点内容</param> public void AddChildNodeCData(string parentNodePath, string elementName, string elementContent) { try { XmlNode parentNode = objXmlDoc.SelectSingleNode(parentNodePath); XmlElement objChildElement = objXmlDoc.CreateElement(elementName); //写入cData数据 XmlCDataSection xcds = objXmlDoc.CreateCDataSection(elementContent); objChildElement.AppendChild(xcds); parentNode.AppendChild(objChildElement); } catch { return; } }
/// <summary> /// fAddCdataToNode /// </summary> /// <param name="aNode"></param> /// <param name="cDataValue"></param> /// <returns></returns> public bool fAddCdataToNode(ref XmlNode aNode, string cDataValue) { XmlNode tempNode; tempNode = DummyXMLObj.CreateCDataSection(cDataValue); //aNode.Value = ""; aNode.AppendChild(tempNode); if (tempNode == null) { return(true); } else { return(false); } }
/// <summary> /// Transforms the Markdown value to HTML. /// </summary> /// <param name="data">The data (Markdown) to transform into HTML.</param> /// <returns>Returns an HTML representation of the data.</returns> public override XmlNode ToXMl(XmlDocument data) { // check that the value isn't null if (this.Value != null && !string.IsNullOrEmpty(this.Value.ToString())) { // transform the markdown into HTML. var mddDataEditor = (DataEditor)this._dataType; string output = mddDataEditor.TextFormatter.Transform(this.Value.ToString()); // return the transformed HTML (as CDATA) return(data.CreateCDataSection(output)); } else { // otherwise render the value as default (in CDATA) return(base.ToXMl(data)); } }
public static XmlNode CreateNode(XmlDocument doc, XmlNodeType nodeType) { Assert.NotNull(doc); switch (nodeType) { case XmlNodeType.CDATA: return doc.CreateCDataSection(@"< & <tag> < ! > & </tag> "); case XmlNodeType.Comment: return doc.CreateComment(@"comment"); case XmlNodeType.Element: return doc.CreateElement("E"); case XmlNodeType.Text: return doc.CreateTextNode("text"); case XmlNodeType.Whitespace: return doc.CreateWhitespace(@" "); case XmlNodeType.SignificantWhitespace: return doc.CreateSignificantWhitespace(" "); default: throw new ArgumentException("Wrong XmlNodeType: '" + nodeType + "'"); } }
private static void NewSnippet(string content, string tabTrigger, string description, string fileName) { XmlDocument doc = new XmlDocument(); { XmlElement rootNode = doc.CreateElement("snippet"); doc.AppendChild(rootNode); { XmlElement contentNode = doc.CreateElement("content"); rootNode.AppendChild(contentNode); { XmlCDataSection cdataNode = doc.CreateCDataSection(content); contentNode.AppendChild(cdataNode); } XmlElement tabTriggerNode = doc.CreateElement("tabTrigger"); rootNode.AppendChild(tabTriggerNode); { XmlText textNode = doc.CreateTextNode(tabTrigger); tabTriggerNode.AppendChild(textNode); } XmlElement scopeNode = doc.CreateElement("scope"); rootNode.AppendChild(scopeNode); { XmlText textNode = doc.CreateTextNode("source.lua"); scopeNode.AppendChild(textNode); } XmlElement descriptionNode = doc.CreateElement("description"); rootNode.AppendChild(descriptionNode); { XmlText textNode = doc.CreateTextNode(description); descriptionNode.AppendChild(textNode); } } } StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); XmlTextWriter xtw = null; try { xtw = new XmlTextWriter(sw); xtw.Formatting = Formatting.Indented; xtw.Indentation = 1; xtw.IndentChar = '\t'; doc.WriteTo(xtw); } catch(Exception e) { throw e; } finally { if(xtw != null) { xtw.Close(); xtw = null; } } File.WriteAllText(saveToFolder + "/" + fileName + ".sublime-snippet", sb.ToString()); }
public static void CDataChildNodeCount() { var xmlDocument = new XmlDocument(); var item = xmlDocument.CreateCDataSection("cdata"); var clonedTrue = item.CloneNode(true); var clonedFalse = item.CloneNode(false); Assert.Equal(0, item.ChildNodes.Count); Assert.Equal(0, clonedTrue.ChildNodes.Count); Assert.Equal(0, clonedFalse.ChildNodes.Count); }
public static void NewlyCreatedCDataNode() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateCDataSection("cdata section"); Assert.Null(node.NextSibling); }
public static void CheckNoChildrenOnCData() { var xmlDocument = new XmlDocument(); Assert.False(xmlDocument.CreateCDataSection("info").HasChildNodes); }
private static XmlCDataSection CreateCDataSection(string value) { var document = new XmlDocument(); return document.CreateCDataSection(value); }
public static void FirstChildOfNewDocumentFragmentWithChildren() { var xmlDocument = new XmlDocument(); var fragment = xmlDocument.CreateDocumentFragment(); var node1 = xmlDocument.CreateComment("comment"); var node2 = xmlDocument.CreateCDataSection("some random text"); fragment.AppendChild(node1); fragment.AppendChild(node2); Assert.Same(node1, fragment.FirstChild); }
public static void FirstChildOfNewCDataSection() { var xmlDocument = new XmlDocument(); Assert.Null(xmlDocument.CreateCDataSection("some clear text").FirstChild); }
protected void GameADEd(object sender, EventArgs e) { XmlDocument xml = new XmlDocument(); try { string xmlPath = Server.MapPath( "/Upload/xml/GameAD.xml" ); if (!File.Exists(xmlPath)) { return; } xml.Load(xmlPath); XmlNode node = xml.SelectSingleNode("//item[@id='" + AdId + "']"); //node.RemoveChild(node.ChildNodes[1]);//先将整个子节点删除 //XmlElement xmelem = xml.CreateElement("Content"); //XmlCDataSection cdata = xml.CreateCDataSection(content.Value); //xmelem.AppendChild(cdata); //node.AppendChild(xmelem); node["Content"].InnerText = ""; XmlCDataSection cdata = xml.CreateCDataSection(content.Value); node.ChildNodes[1].AppendChild(cdata); xml.Save(xmlPath); CommonManager.Web.RegJs(this, "alert('修改成功!');location.href='gameadsetting.aspx';", false); } catch(Exception ex) { CommonManager.Web.RegJs(this, "alert(\"修改失败!"+ex.Message.Substring(0,39)+"\");location.href=location.href;", false); } }