2012-01-29 51 views
1

我已經閱讀了很多這裏關於XML的主題,並嘗試了一些,但我仍然無法得到這個問題的工作。
我必須從我的xml文件中列出「Items」並將其加載到ListView中。我的項目是在Pocket PC上製作的。這裏是示例xml內容。如何通過XDocument在c#中列出xml元素?

<? xml version="1.0" encoding="utf-8" ?> 
<Library> 
    <Item> 
     <Name>Picture</Name> 
     <FullPath>\My Device\My Documents\Picture</FullPath> 
     <SystemFullpath>\Program Files\Explorer\Library</SystemFullpath> 
     <Created>0001-01-01T00:00:00</Created> 
    </Item> 
    <Item> 
     <Name>Video</Name> 
     <FullPath>\My Device\My Documents\Video</FullPath> 
     <SystemFullpath>\Program Files\Explorer\Library</SystemFullpath> 
     <Created>0001-01-01T00:00:00</Created> 
    </Item> 
    <Item> 
     <Name>File</Name> 
     <FullPath>\My Device\My Documents\File</FullPath> 
     <SystemFullpath>\Program Files\Explorer\Library</SystemFullpath> 
     <Created>0001-01-01T00:00:00</Created> 
    </Item> 
</Library> 

我想補充一個項目的方式:

public bool AddLibrary(Library lib) 
{ 
    try 
    { 
     XDocument xDoc = XDocument.Load(fileName); 
     XElement xe = new XElement("Item", 
      new XElement("Name", lib.Name), 
      new XElement("Fullpath", lib.Fullpath), 
      new XElement("SystemFullpath", lib.SystemFullpath), 
      new XElement("Created", lib.Created)); 

     xDoc.Element("Library").Add(xe); 
     xDoc.Save(fileName); 
     return true; 
    } 
    catch { return false; } 
} 

圖書館實體:

public class Library 
{ 
    public Library() { } 

    // Unique 
    public string Name { get; set; } 

    public string Fullpath { get; set; } 

    public string SystemFullpath { get; set; } 

    public DateTime Created { get; set; } 

    public List<Items> Items { get; set; } 
} 

以及用於獲取項目的代碼,返回一個錯誤:

public List<Library> RetrieveAllLibrary() 
{ 
    List<Library> libList = new List<Library>(); 
    if (File.Exists(fileName)) 
    { 
     XDocument xDoc = XDocument.Load(fileName); 

     var items = from item in xDoc.Descendants("Item") 
        select new 
        { 
         Name = item.Element("Name").Value, 
         FullPath = item.Element("FullPath").Value, 
         Created = item.Element("Created").Value 
        }; 

     if (items != null) 
     { 
      foreach (var item in items) 
      { 
       Library lib = new Library(); 
       lib.Name = item.Name; 
       lib.Fullpath = item.FullPath; 
       lib.Created = DateTime.Parse(item.Created); 
       libList.Add(lib); 
      } 
     } 
    } 
    return libList; 
} 

錯誤說:

enter image description here

我希望我能解釋清楚。感謝幫助!!

回答

2

你的問題是這樣的一行:

new XElement("Fullpath", lib.Fullpath), 

名稱鍵入一個小寫的「P」,後來你習慣"FullPath"用大寫字母「P」。

如果要保留數據,還應該將XML文件中的所有「FullPath」替換爲「FullPath」。

+0

是這樣嗎?哇!你說對了。我甚至沒有注意到這一點。謝謝! – fiberOptics 2012-01-29 01:02:54

相關問題