C# XML添加删除/SelectNodes/xpath
生活随笔
收集整理的這篇文章主要介紹了
C# XML添加删除/SelectNodes/xpath
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
SelectNodes中的XPath
//從當(dāng)前節(jié)點(diǎn)的兒子節(jié)點(diǎn)中選擇名稱為 item 的節(jié)點(diǎn)。 SelectNodes("item")//從根節(jié)點(diǎn)的兒子節(jié)點(diǎn)中選擇名稱為 item 的節(jié)點(diǎn)。 SelectNodes("/item")// 從任意位置的節(jié)點(diǎn)上選擇名稱為 item 的節(jié)點(diǎn)。要重點(diǎn)突出這個(gè)任意位置,它不受當(dāng)前節(jié)點(diǎn)的影響,也就是說假如當(dāng)前節(jié)點(diǎn)是在第 100 層(有點(diǎn)夸張),也可以選擇第一層的名稱為 item 的節(jié)點(diǎn)。 SelectNodes("//item")// 在 SelectNodes("//item") 的基礎(chǔ)上,增加了一個(gè)限制,就是要求擁有 name 屬性。 SelectNodes("//item[@name]")// 在 SelectNodes("//item[@name]") 的基礎(chǔ)上,增加了一個(gè)限制,就是要求 name 屬性值為 111。注意語法中有引號(hào);如果沒有引號(hào),則表示是數(shù)字類型,對(duì)于數(shù)字類型可以使用大于號(hào)、小于號(hào)等,比如:SelectNodes("//item[@v>333]")。 SelectNodes("//item[@name='111']")//*******進(jìn)階版************** // 模糊匹配 // 使用contains, 表示label屬性內(nèi)容包含caseSuite變量?jī)?nèi)容 string xpathStr = string.Format(@"//TestSuite[contains(@label,'{0}')]", caseSuite); XmlNodeList removeSuiteInfoList = suiteListNode.SelectNodes(xpathStr);// 可以邏輯運(yùn)算 /Root//Person[contains(Blog,'cn') and contains(@ID,'01')]SelectNodes
如果xml里沒有“xxx”節(jié)點(diǎn),nodeList.Count會(huì)返回0,而不是null或error
XmlDocument xmlDocument = new XmlDocument();xmlDocument.Load(@"test.xml");XmlNodeList nodeList = xmlDocument.SelectNodes(@"//UnitTest/XXX");Console.WriteLine(nodeList.Count.ToString());Console.ReadKey();?
xml文件創(chuàng)建與保存
XmlDocument planDoc = new XmlDocument();planDoc.AppendChild(planDoc.CreateXmlDeclaration("1.0", "UTF-8", null));//創(chuàng)建根目錄 XmlElement planRoot = planDoc.CreateElement(PlanSuiteList);//保存至PlanFullName planDoc.Save(PlanFullName);?
創(chuàng)建節(jié)點(diǎn)以及添加屬性
//創(chuàng)建節(jié)點(diǎn) XmlElement memberTestSuite = planDoc.CreateElement(TestSuite); //設(shè)置屬性 memberTestSuite.SetAttribute(EachFlowLabel, label);//創(chuàng)建子節(jié)點(diǎn) XmlElement childName = planDoc.CreateElement(EachFlowName); childName.InnerText = suiteName;//子節(jié)點(diǎn)添加memberTestSuite.AppendChild(childName);//添加到根節(jié)點(diǎn) planRoot.AppendChild(memberTestSuite);//根節(jié)點(diǎn)添加到xml文件planDoc.AppendChild(planRoot);// xmlnode 添加節(jié)點(diǎn) XmlNode projectInfoNode = projectInfoDocument.SelectSingleNode(@"//ProjectInfo"); XmlElement newNodeElement = projectInfoDocument.CreateElement(nodeName); newNodeElement.InnerText= testerNode.InnerText;projectInfoNode.AppendChild(newNodeElement);?
刪除節(jié)點(diǎn)
//刪除子節(jié)點(diǎn) XmlNode suiteListNode = planDocument.SelectSingleNode(@"//PlanSuiteList");suiteListNode.RemoveChild(suiteNode);?
參考:https://blog.csdn.net/nnn_net/article/details/69584358
總結(jié)
以上是生活随笔為你收集整理的C# XML添加删除/SelectNodes/xpath的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: django09: ORM以及CSRF(
- 下一篇: C# 字符串操作:split、subst