2014-01-06 86 views
1

我有這樣Visual Basic中的LINQ to XML不能選擇對象

var books = System.Xml.Linq.XDocument.Load(_filename).Root.Elements("Book").Select(
      x => new Book(
       (string)x.Element("Title"), 
       (string)x.Element("Author"), 
       (string)x.Element("Publisher"), 
       (string)x.Element("ISBN"))); 

return books; 

我把它轉換成一個VB C#代碼,但我不知道我怎麼能寫出選擇部分。

Dim books = System.Xml.Linq.XDocument.Load(_filename).Root.Elements("Book"). 
      Select(/****what should i write here ***/) 
Return books 
+0

您需要使用'DirectCast'將元素轉換爲字符串。 – XN16

回答

0

另外重要的一點是,你可能尋找XElement.Value

x.Element("Title").Value 

不是

x.Element("Title") 

因爲第一個將返回

"My Book" 

,第二個 - 是這樣的:

"<Title>My Book</Title>" 
1

請嘗試以下

.Select(Function (x) 
    Return new Book(
    CType(x.Element("Title"), String), 
    CType(x.Element("Author"), String), 
    CType(x.Element("Publisher"), String), 
    CType(x.Element("ISBN"), String)) 
    End Function) 
+0

如果我不添加「.Value」(如x.Element(「Title」)。Value)我得到一個錯誤,如 「類型'System.Xml.Linq.XElement'的值不能轉換爲'String'」 – AndroCoder

+0

@AndroCoder使用CType而不是DirectCast,將會更新 – JaredPar

0

最後我做了我這樣的代碼,它現在是正確的

.Select(Function(x) 
      Return New Book(
       DirectCast(x.Element("Title").Value, String), 
       DirectCast(x.Element("Author").Value, String), 
       DirectCast(x.Element("Publisher").Value, String), 
       DirectCast(x.Element("ISBN").Value, String)) 
     End Function) 

DirectCast和價值是非常重要的