2010-10-28 67 views
1

我在看this問題,它給了我約80%的需求。對我而言,「問題」在於我的XML結構不同,我不太清楚我將如何使用Linq來獲得我所需要的內容。什麼Linq到XML我需要將XML綁定到Silverlight Datagrid

我的XML看起來是這樣的(順便說一句,它通過的ConvertTo XML的PowerShell命令生成)

<?xml version="1.0"?> 
<Objects> 
    <Object> 
    <Property Name="Name">CompiledCode.ps1</Property> 
    <Property Name="LastWriteTime">5/21/2009 6:59:16 PM</Property> 
    </Object> 
    <Object> 
    <Property Name="Name">ComputerDrawing.ps1</Property> 
    <Property Name="LastWriteTime">1/13/2010 7:52:44 AM</Property> 
    </Object> 
</Objects> 

我試圖綁定到一個Silverlight DataGrid中,使列名會是「名」和「LastWriteTime」,行將有屬性標籤中的值。對於第一個,名稱將被編譯Code.ps1和LastWriteTime將是「2009年5月21日下午6時59分16秒」

答案上述問題,有這個方法

private Status GetStatus(XElement el) 
     { 
      Status s = new Status(); 
      s.Description = el.Attribute("Description").Value; 
      s.Date = DateTime.Parse(el.Attribute("Date").Value); 
      return s; 
     } 

我創建了我自己的名爲腳本的類,它有一個名稱和一個日期,但我想弄清楚我需要填充我的數據網格的元素或屬性。

回答

1

這是你所需要的基本要點是: -

private Scripts GetScripts(XElement el) 
{ 
    Scripts s = new Scripts() 

    s.Name = (string)el.Elements("Property") 
     .Where(e => (string)e.Attribute("Name") == "Name") 
     .FirstOrDefault(); 

    string lastWriteTime = (string)el.Elements("Property") 
     .Where(e => (string)e.Attribute("Name") == "LastWriteTime") 
     .FirstOrDefault(); 

    s.LastWriteTime = DateTime.ParseExact(lastWriteTime, "M/d/yyyy h:m:s tt", CultureInfo.InvariantCulture); 
} 

你可能會想LastWriteTime是一個DateTime所以你可能要到的地方是在一個intermediatory字符串和詳細的使用解析。