2012-01-29 59 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