簡體   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