2012-01-29 6 views
1

xmlに関して多くの話題を読んだことがありますが、まだ試してみることができません。
私はXMLファイルから "Items"をリストし、ListViewにロードする必要があります。私のプロジェクトはPocket-PCで作られています。ここにサンプルのXMLコンテンツがあります。C#でXDocument経由で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

私はそれをうまく説明したいと思います。手伝ってくれてありがとう!!

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

名は小文字の「P」と入力した、と後であなたが資本「P」と"FullPath"を使用している:

答えて

2

あなたの問題は、このラインです。

データを保持する場合は、XMLファイル内のすべての "フルパス"を "フルパス"に置き換える必要があります。

+0

そうですか?うわー!あなたはそれを持っています。私はそれに気付かなかった。ありがとう! – fiberOptics

関連する問題