2013-03-29 136 views
0

XML文件是这样的,有大约20个像这样的节点(模块)。从C#中的节点读取XML文件到Array节点

<list> 
<module code="ECSE502"> 
<code>ECSE502</code> 
<name>Algorithms and Data structures</name> 
<semester>1</semester> 
<prerequisites>none</prerequisites> 
<lslot>0</lslot> 
<tslot>1</tslot> 
<description>all about algorythms and data structers with totorials and inclass tests</description> 
</module>  
</list> 

我做了下面的代码。但是当我调试它时,它甚至没有进入函数的foreach。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 

namespace ModuleEnrolmentCW 
{ 
    class XMLRead 
    { 

     public string[] writeToXML(string s) 
     { 
      string text = s;   
      string[] arr = new string[6]; 

      XmlDocument xml = new XmlDocument(); 
      xml.Load("modules.xml"); 

      XmlNodeList xnList = xml.SelectNodes("list/module[@code='" + text + "']"); 
      foreach (XmlNode xn in xnList) 
      { 
       arr[0] = xn.SelectSingleNode("code").InnerText; 
       arr[1] = xn.SelectSingleNode("name").InnerText; 
       arr[2] = xn.SelectSingleNode("semester").InnerText; 
       arr[3] = xn.SelectSingleNode("prerequisites").InnerText; 
       arr[4] = xn.SelectSingleNode("lslot").InnerText; 
       arr[5] = xn.SelectSingleNode("tslot").InnerText;        
      } 

      return arr; 
     } 


    } 
} 

请告诉我哪里错了?

这里是代码的其余部分

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace ModuleEnrolmentCW 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 
     string selected; 
     private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      XMLRead x = new XMLRead(); 
      selected = (string)listBox1.SelectedItem; 
      string[] arr2 = x.writeToXML(selected); 

      label11.Text = arr2[0]; 

     } 
    } 
} 
+1

您的代码适合我。你是否将正确的代码传递给'writeToXML'? – polybios

+0

你的代码正在运行你有没有测试'text'的值是一个有效的代码' –

+0

调试你的应用程序,在'xml.Load'后面加一个断点并确认'text'和'xml'的值。 –

回答

0

发现错误。我正在向writeToXML方法传递一个错误的值。没有通过代码,我已通过名称

1

这条线:

XmlNodeList xnList = xml.SelectNodes("list/module[@code='" + text + "']"); 

应改为:

XmlNodeList xnList = xml.SelectNodes("list/module"); //Does not answer full scope of the question 

编辑以下问题的重读:

OP的代码在我的测试中工作正常。文件路径不正确,或者传入textstring s与您正在读取节点的Code值的情况匹配。

SelectNodesXPath因为你有它是区分大小写的。

您似乎正在使用XPath V1.0,如果出现这种问题,它似乎不支持开箱即用不敏感。请参阅此链接进行区分大小写的XPath搜索方式:http://blogs.msdn.com/b/shjin/archive/2005/07/22/442025.aspx

也看到此链接:case-insensitive matching in xpath?

+1

这对于这个孤立的例子是有效的,但我认为他很清楚他希望能够通过它们的'code'属性指定模块(假设这是字符串参数的唯一用途)... –

+0

@AntP我只是重读的问题,看到 – jordanhill123

+0

你如何传递的,他想重读 –

1

确保您指定的XML文件正确的路径。

它正在为我工​​作。

enter image description here

+0

我做到了, xml.Load(后读取节点 – Ravindu

+0

我已经在我的机器上测试过它正在工作。尝试调试您的代码。他们必须是其他问题。 –

1

你的代码是正确的,如果输入的是真的,你出的一个,和s指向一个实际存在的代码。由于您是通过相对路径指向文件,因此请确保您正在加载您真正期望的文件。