0

XML文件是这样的,大约有20个这样的节点(模块)。

<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];

        }
    }
}
4

4 回答 4

1

这一行:

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

应该读:

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

重新阅读问题后进行编辑:

OP 的代码在我的测试中运行良好。文件路径不正确,或者string s传入的值与您正在读取节点text的值的大小写匹配。Code

正如你所拥有的SelectNodes XPath那样,它区分大小写。

您似乎正在使用 XPath V1.0,如果这是一个问题,它似乎不支持开箱即用的不区分大小写。有关执行不区分大小写的 XPath 搜索的方法,请参阅此链接:http: //blogs.msdn.com/b/shjin/archive/2005/07/22/442025.aspx

另请参阅此链接:xpath 中不区分大小写的匹配?

于 2013-03-29T09:55:20.567 回答
1

确保为 xml 文件指定正确的路径。

它对我有用。

在此处输入图像描述

于 2013-03-29T09:56:46.307 回答
1

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

于 2013-03-29T09:58:31.767 回答
0

发现错误。我向 writeToXML 方法传递了错误的值。安装了传递代码,我已经传递了名字

于 2013-03-29T10:24:56.180 回答