2012-09-10 31 views
0

嘗試第一次使用Linq到XML並遇到一些問題。我有這個XML文件需要被讀取和用於各種任務。該文件包含一個名爲「接口」的實體列表。首先,我想顯示這些接口的名稱列表。如何寫簡單的查詢到XElement?

下面是XML文件:

<?xml version="1.0" encoding="utf-8" ?> 
<InterfaceList> 
    <Interface> 
    <InterfaceName>Account Lookup</InterfaceName> 
    <RequestXSD>ALREQ.xsd</RequestXSD> 
    <ResponseXSD>ALRES.xsd</ResponseXSD> 
    </Interface> 
    <Interface> 
    <InterfaceName>Balance Inquiry</InterfaceName> 
    <RequestXSD>BIREQ.xsd</RequestXSD> 
    <ResponseXSD>BIRES.xsd</ResponseXSD> 
    </Interface> 
</InterfaceList> 

下面是查詢代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml.Linq; 

namespace Stub { 
    public class InterfaceList : XElement { 

     public void GetInterfaceNameList() { 
      var v = from interface in this.Elements("Interface") 
       select interface.Element("InterfaceName").Value; 
     } 
    } 
} 

的想法是從文件加載InterfaceList,然後用它來查詢任何我可能需要。 問題是我收到查詢中的所有內容的錯誤消息。這裏有幾個:

  • 錯誤14「從」這個名字在目前情況下
  • 錯誤15類型或命名空間名稱「中選擇」找不到不存在(是 你失蹤使用指令或程序集引用一個?) 錯誤
  • 錯誤16「System.Xml.Linq.XElement.Value」是「屬性」,但用於 像一個「類型」

什麼錯在這裏的?

+6

fyi,'interface'是一個C#關鍵字。 –

+0

謝謝,這是答案。注意添加它,以便我可以標記它? – Yoav

回答

1

如果你想打電話給你的變量「接口」(這是一個保留字),你需要逃避它,就像這樣:

var v = from @interface in this.Elements("Interface") 
     select @interface.Element("InterfaceName").Value; 

可能會更好,只是將其重命名雖然....