繁体   English   中英

在C#中从XML文件逐节点读取到Array节点

[英]Read from a XML file to an Array node by node in C#

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

        }
    }
}

这行:

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

应该读:

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

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

OP的代码在我的测试中工作正常。 文件路径不正确,或者传递到text中的string s与您读取节点所依据的Code值的大小写匹配。

您拥有的SelectNodes XPath区分大小写。

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

另请参见以下链接: xpath中是否区分大小写?

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

它为我工作。

在此处输入图片说明

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

发现错误。 我将错误的值传递给writeToXML方法。 插入了代码,我已经通过了名称

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM