2012-01-31 43 views
0

我一直在尋找24小時的答案,但我沒有找到它。我是C#的新手。我發現了一個教程,從那裏我已經使用這個代碼:從XML文件導入數據到字符串

XDocument loadedCustomData = XDocument.Load("PeopleCustom.xml"); 
var filteredData = from c in loadedCustomData.Descendants("Person") 
          where c.Attribute("Age").Value == current.ToString() 
          select new Person 
          { 
           FirstName = (string)c.Attribute("FirstName").Value, 
          }; 

listBox1.ItemsSource = filteredData; 
public class Person 
    { 
     string firstname; 
     string lastname; 
     int age; 

     public string FirstName 
     { 
      get { return firstname; } 
      set { firstname = value; } 
     } 

     public string LastName 
     { 
      get { return lastname; } 
      set { lastname = value; } 
     } 


     public int Age 
     { 
      get { return age; } 
      set { age = value; } 
     } 


    } 

XML是這樣的:

<People> 
<Person 
    FirstName="Kate" 
    LastName="Smith" 
    Age="1" /> 
<Person 
     ... 
       /> 
</People> 

它的工作原理,但它把所有的輸出到列表框中。我想要字符串。我試圖從列表框中獲取字符串(就像這個listBox1.Items [0] .ToString();),但我得到的是這樣的:ProjectName.MainPage + Person。我也試圖從filteredData中獲取它,但沒有成功。 有什麼辦法從XML獲取數據到字符串?預先感謝您的回答

回答

1

這個代碼

XDocument loadedCustomData = XDocument.Load("PeopleCustom.xml"); 
var filteredData = from c in loadedCustomData.Descendants("Person") 
          where c.Attribute("Age").Value == current.ToString() 
          select new Person 
          { 
           FirstName = (string)c.Attribute("FirstName").Value, 
          }; 

使Person對象的列表:select New Person{.....}

如果你想Person的名字的字符串列表,那麼您需要做的是改變什麼對象LINQ是創造....

select (string)c.Attribute("FirstName").Value); 
現在

,它使從一個新的字符串210屬性。

這個linq運行後,你基本上會有一個linq對象,它會產生一個字符串列表。如果你想有一個名單,然後修改如下:

XDocument loadedCustomData = XDocument.Load("PeopleCustom.xml"); 
var filteredData =(from c in loadedCustomData.Descendants("Person") 
          where c.Attribute("Age").Value == current.ToString() 
          select (string)c.Attribute("FirstName").Value).ToList(); 

,如果你想在列表中的第一個字符串...

filterdData.First(); 
+0

謝謝你,成功了! – Nikmaster 2012-01-31 02:25:27

+0

然後請將此標記爲接受的答案! :) – 2012-01-31 02:28:30

+0

對不起,我不能投票了你的答案,我沒有足夠的代表。再次感謝 – Nikmaster 2012-01-31 02:28:40

0

從你得到listBox1.items包含輸出對象的人,所以你可以嘗試

var name = ((Person)listBox1.Items[0]).FirstName; 

這應該給你的價值

+0

對不起,這沒有奏效。它說沒有定義名字。 – Nikmaster 2012-01-31 02:26:56