查了一些,都是根据XML属性来访问指定节点,我这想根据节点索引来访问XML
首先上XML样式
1 <?xml version="1.0" encoding="utf-8" ?> 2 <FeatureClasses> 3 <FeatureClass name = "t_room"></FeatureClass> 4 <FeatureClass name = "t_floor"></FeatureClass> 5 <FeatureClass name = "t_in_wall"></FeatureClass> 6 <FeatureClass name = "t_in_toilet"></FeatureClass> 7 <FeatureClass name = "t_in_elevator"></FeatureClass> 8 </FeatureClasses>
然后上C#访问代码
1 public string ReadXmlNode(string filename,int i) 2 { 3 XmlDocument xmlDoc = new XmlDocument(); 4 string str=""; 5 try 6 { 7 xmlDoc.Load(filename); 8 XmlNode root = xmlDoc.SelectSingleNode("//FeatureClass"); 9 for (int j = 0; j <= i; j++) 10 { 11 str = root.Attributes["name"].Value; 12 root = root.NextSibling; 13 } 14 } 15 catch (Exception e) 16 { 17 MessageBox.Show("" + e); //显示错误信息 18 return str; 19 } 20 return str; 21 }
其实就是遍历啦,没找到根据索引访问的方法,只有ChildNodes访问子节点索引。
然后在你的主程序for循环中调用这个方法
string openLyer = ReadXmlNode(pathName,i);
再上一些路径写法
1 string fileName = AppDomain.CurrentDomain.BaseDirectory;//获得当前路径debug 2 string fileNameplus = System.IO.Path.GetFullPath("..\..\..");//往上返回 3 string pathName = fileNameplus + "\bin\Config\LayerName.xml";//拼接路径
写的比较简单详细。有不对地方还请指正。