SelectNodes中的XPath
//从当前节点的儿子节点中选择名称为 item 的节点。
SelectNodes("item")
//从根节点的儿子节点中选择名称为 item 的节点。
SelectNodes("/item")
// 从任意位置的节点上选择名称为 item 的节点。要重点突出这个任意位置,它不受当前节点的影响,也就是说假如当前节点是在第 100 层(有点夸张),也可以选择第一层的名称为 item 的节点。
SelectNodes("//item")
// 在 SelectNodes("//item") 的基础上,增加了一个限制,就是要求拥有 name 属性。
SelectNodes("//item[@name]")
// 在 SelectNodes("//item[@name]") 的基础上,增加了一个限制,就是要求 name 属性值为 111。注意语法中有引号;如果没有引号,则表示是数字类型,对于数字类型可以使用大于号、小于号等,比如:SelectNodes("//item[@v>333]")。
SelectNodes("//item[@name='111']")
//*******进阶版**************
// 模糊匹配
// 使用contains, 表示label属性内容包含caseSuite变量内容
string xpathStr = string.Format(@"//TestSuite[contains(@label,'{0}')]", caseSuite);
XmlNodeList removeSuiteInfoList = suiteListNode.SelectNodes(xpathStr);
// 可以逻辑运算
/Root//Person[contains(Blog,'cn') and contains(@ID,'01')]
SelectNodes
如果xml里没有“xxx”节点,nodeList.Count会返回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文件创建与保存
XmlDocument planDoc = new XmlDocument();
planDoc.AppendChild(planDoc.CreateXmlDeclaration("1.0", "UTF-8", null));
//创建根目录
XmlElement planRoot = planDoc.CreateElement(PlanSuiteList);
//保存至PlanFullName
planDoc.Save(PlanFullName);
创建节点以及添加属性
//创建节点
XmlElement memberTestSuite = planDoc.CreateElement(TestSuite);
//设置属性
memberTestSuite.SetAttribute(EachFlowLabel, label);
//创建子节点
XmlElement childName = planDoc.CreateElement(EachFlowName);
childName.InnerText = suiteName;
//子节点添加
memberTestSuite.AppendChild(childName);
//添加到根节点
planRoot.AppendChild(memberTestSuite);
//根节点添加到xml文件
planDoc.AppendChild(planRoot);
// xmlnode 添加节点
XmlNode projectInfoNode = projectInfoDocument.SelectSingleNode(@"//ProjectInfo");
XmlElement newNodeElement = projectInfoDocument.CreateElement(nodeName);
newNodeElement.InnerText= testerNode.InnerText;
projectInfoNode.AppendChild(newNodeElement);
删除节点
//删除子节点
XmlNode suiteListNode = planDocument.SelectSingleNode(@"//PlanSuiteList");
suiteListNode.RemoveChild(suiteNode);