2012-02-07 35 views
6

Thao tác này tải một tập hợp các giá trị từ một tệp XML và đặt chúng vào một lớp để lưu trữ. Tôi đang cố gắng tìm ra cách để xuất các giá trị như một danh sách để tôi có thể đặt chúng vào một Listbox.Xuất lớp giá trị được lưu trữ vào danh sách

Tôi nghĩ rằng sẽ có một cách dễ dàng như phương thức .ToList() hoặc để có thể thông qua các chuỗi trong lớp (không có công cụ GetEnumerator). Tôi đã có thể tìm ra rằng Foreach giấu một số sự phức tạp nhưng không phải để làm những gì tôi muốn.

Tôi đã tìm kiếm trực tuyến với vô ích (thiếu các thuật ngữ chính xác có thể), tiếc là tôi rời khỏi cuốn sách C# tham khảo của tôi tại nơi làm việc:/

có nhiều đánh giá cao một con trỏ đi đúng hướng, Cảm ơn.

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; 
using System.IO; 
using System.Xml; 

namespace ThereIsOnlyRules 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     try 
     { 
      listBox1.Items.Clear(); 

      string path = "characterXML.xml"; 
      FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
      System.Xml.XmlDocument CXML = new System.Xml.XmlDocument(); 

      CXML.Load(fs); 

      //Get the number of elements 
      XmlNodeList elemList = CXML.GetElementsByTagName("unit"); 

      //foreach (var element in elemList) 
      //{ 
      // listBox1.Items.Add(element); 
      //} 

      for (int i = 0; i < elemList.Count; i++) 
      { 
       UnitAttributes attributes = new UnitAttributes(); 

       attributes.army = elemList[i].Attributes["army"].Value; 
       attributes.category = elemList[i].Attributes["category"].Value; 
       attributes.type = elemList[i].Attributes["type"].Value; 
       attributes.composition = elemList[i].Attributes["composition"].Value; 
       attributes.WS = elemList[i].Attributes["WS"].Value; 
       attributes.BS = elemList[i].Attributes["BS"].Value; 
       attributes.T = elemList[i].Attributes["T"].Value; 
       attributes.W = elemList[i].Attributes["W"].Value; 
       attributes.I = elemList[i].Attributes["I"].Value; 
       attributes.A = elemList[i].Attributes["A"].Value; 
       attributes.LD = elemList[i].Attributes["LD"].Value; 
       attributes.save = elemList[i].Attributes["Save"].Value; 
       attributes.armour = elemList[i].Attributes["armour"].Value; 
       attributes.weapons = elemList[i].Attributes["weapons"].Value; 
       attributes.specialrules = elemList[i].Attributes["specialrules"].Value; 
       attributes.transport = elemList[i].Attributes["transport"].Value; 
       attributes.options = elemList[i].Attributes["options"].Value; 

       //foreach (string item in attributes) 
       //{ 

        //unit.Add(item); 
       //} 
       //listBox1.Items.AddRange(attributes) 

      } 

      //Close the filestream 
      fs.Close(); 
     } 
     catch (Exception ex) 
     { 

     } 
    } 
} 
} 

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

namespace ThereIsOnlyRules 
{ 
class UnitAttributes 
{ 
    public string army { get; set; } 
    public string category { get; set; } 
    public string type { get; set; } 
    public string composition { get; set; } 
    public string WS { get; set; } 
    public string BS { get; set; } 
    public string T { get; set; } 
    public string W { get; set; } 
    public string I { get; set; } 
    public string A { get; set; } 
    public string LD { get; set; } 
    public string save { get; set; } 
    public string armour { get; set; } 
    public string weapons { get; set; } 
    public string specialrules { get; set; } 
    public string transport { get; set; } 
    public string options { get; set; } 
    } 
} 

<?xml version="1.0"?> 
<config> 
<unit 
army="Tyranids" 
category="Troops" 
type="Infantry" 
composition="10-30" 
WS="3" 
BS="3" 
T="3" 
W="1" 
I="4" 
A="1" 
LD="6" 
Save="6+" 
armour="Chitin" 
weapons="Claws and Teeth, Fleshborer" 
specialrules="Instictive Behaviour - Lurk, Move Through Cover" 
transport="If the brood consists of 20 models or less, it may take a Mycetic Spore." 
options="Strangleweb, Spinefists, Spike rifle, Devourer, Adrenal Glands, Toxin Sacs" 
> 
Termagant Brood 
</unit> 
<unit 
army="Tyranids" 
category="Troops" 
type="Infantry" 
composition="10-30" 
WS="3" 
BS="3" 
T="3" 
W="1" 
I="5" 
A="2" 
LD="6" 
Save="6+" 
armour="Chitin" 
weapons="Scything Talons" 
specialrules="Instictive Behaviour - Feed, Bounding Leap, Fleet, Move Through Cover" 
transport="If the brood consists of 20 models or less, it may take a Mycetic Spore." 
options="Adrenal Glands, Toxin Sacs" 
> 
Hormagaunt Brood 
</unit> 
</config> 
+1

'XmlNodeList' không thực hiện' IEnumerable', do đó, 'foreach' của bạn sẽ hoạt động. – svick

Trả lời

3

Các thành viên của trường hoặc thuộc tính lớp học của bạn phải không? Dù bằng cách nào, một chút phản ánh và Linq sẽ cho phép bạn liệt kê thông qua các thành viên dữ liệu trong lớp của bạn, sau khi bạn đã hydrated một thể hiện của nó từ tệp XML của bạn.

var fieldDictionary = 
    (from f in typeof(UnitAttributes).GetFields() 
    select new {Name = f.Name, Value = (string)(f.GetValue(attributes))}) 
    .ToDictionary(x=>x.Name, x=>x.Value); 

fieldDictionary bây giờ là một Dictionary<string, string> (mà là một IEnumerable<KeyValuePair<string, string>>), mà phải phù hợp với nạp vào một ListBox.

Được thông báo; phản ánh chậm. Nó sẽ được nhiều hơn nữa thích hợp hơn cho bạn để sửa đổi hoặc mở rộng lớp UnitAttributes của bạn để thực hiện IEnumerable (có thể là một Tuple, có thể là một KeyValuePair). Nó cũng sẽ cho phép bạn liệt kê các thuộc tính của một thể hiện của lớp theo đúng thứ tự bạn muốn, thay vì thứ tự mà chúng được định nghĩa, hoặc bởi một số dữ liệu FieldInfo/PropertyInfo khác như tên của trường.

Cũng lưu ý rằng trường không phải là thuộc tính và ngược lại. Nếu bạn có một kết hợp các thuộc tính và các trường công khai trên lớp của bạn, tôi rất muốn giới thiệu tiêu chuẩn hóa cho một hoặc khác; nếu không bạn sẽ phải phản ánh BOTH một danh sách các thuộc tính và một danh sách các trường sử dụng hai câu lệnh Linq ở trên (với chi phí gấp đôi thời gian chạy), và sẽ không có cơ hội nào trong chúng được định nghĩa tùy chỉnh gọi món.

2

Bạn sẽ tiết kiệm cho mình rất nhiều thời gian và công sức nếu bạn sử dụng bộ nối tiếp phổ biến như XmlSerializer để xử lý việc chuyển đổi đối tượng của bạn sang/từ chuỗi. Bạn không phải viết loại mã này từ đầu.

+0

Đồng ý, nhưng tôi nghĩ điểm mấu chốt của câu hỏi là cách liệt kê thông qua dữ liệu ở dạng đối tượng chứ không phải XML. – KeithS

+0

Tôi vẫn đánh giá cao việc được bảo, tôi chỉ đang đọc một cái gì đó tương tự ở nơi khác. – Amicable

Các vấn đề liên quan