Vb.net Visual Basic LinQ to XML无法选择对象
我有这样的C代码Vb.net Visual Basic LinQ to XML无法选择对象,vb.net,linq,Vb.net,Linq,我有这样的C代码 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("Pub
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,但我不知道如何编写选择部分
Dim books = System.Xml.Linq.XDocument.Load(_filename).Root.Elements("Book").
Select( /****what should i write here ***/ )
Return books
试试下面的方法
.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)
另一个要点是,您可能正在查找
XElement.Value
:
x.Element("Title").Value
而不是
x.Element("Title")
因为第一个会回来
"My Book"
还有第二个,比如:
"<Title>My Book</Title>"
“我的书”
最后,我将我的代码做成这样,现在它是正确的
.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和Value很重要您需要使用
DirectCast
将元素转换为字符串。如果我不添加“.Value”(如x.element(“Title”).Value)我会收到一个错误,如“Value of type'System.Xml.Linq.XElement'无法转换为'string'。@AndroCoder使用CType代替DirectCast,将更新