使用 Linq to Xml 构建对象列表
我正在尝试使用 linq 从 XML 文件中提取值来创建对象列表。 XML 文件如下所示。
<RootNode>
<Node1>
<Node2>
<results>
<work>
<title>title1</title>
<author>author</author>
<image_url>image</image_url>
</work>
...
</RootNode>
XDocument results = XDocument.Load("url");
根据搜索,这些“工作”节点(以及后续子节点)可能会多次出现。对于每次出现的“作品”,我想提取标题/作者/图像值来构建一个简单的书籍对象:
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public string ImageUrl { get; set; }
}
现在我可以迭代 xml 文件并使用类似这样的东西挑选出单独的值:
foreach (XElement element in results.Descendants("title"))
{
string title = element.Value;
}
但是当我想构建一个我一直在尝试各种类似的书籍列表:
List<Book> books =
(from book in results.Descendants("work")
select new Book
{
Title = book.Element("title").Value,
Author = book.Element("name").Value,
ImageUrl = book.Element("image_url").Value,
}).ToList<Book>();
但是我不断收到空引用异常。任何指出我出错的地方的指示将不胜感激。
凯文.
编辑
大家好,问题出在 XML 文件上,而不是 linq 语句上。谢谢。
I am trying to extract values from an XML file using linq to create a list of objects. The XML File looks like this.
<RootNode>
<Node1>
<Node2>
<results>
<work>
<title>title1</title>
<author>author</author>
<image_url>image</image_url>
</work>
...
</RootNode>
XDocument results = XDocument.Load("url");
There can be multiple occurrences of these 'work' nodes (and subsequent child nodes) depending on the search. For each occurrence of 'work' I want to extract the title/author/image values to build a simple book object:
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public string ImageUrl { get; set; }
}
Now I can iterate through the xml file and pick out indivual values using something like this:
foreach (XElement element in results.Descendants("title"))
{
string title = element.Value;
}
but as I want to build a list of books I have been trying various things much like this:
List<Book> books =
(from book in results.Descendants("work")
select new Book
{
Title = book.Element("title").Value,
Author = book.Element("name").Value,
ImageUrl = book.Element("image_url").Value,
}).ToList<Book>();
However I keep getting a null reference exceptionfor this. Any pointers of where I am going wrong would be greatly appreciated.
Kevin.
EDIT
Hi guys turns out the problem was with the XML file and not the linq statement. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过几次小的修改后它对我有用:
It works for me after several minor modifications:
空值是指空引用异常吗?我发现在您的代码中您正在寻找“image_url”元素,但在您的示例中有一个“image”元素。
By null value do you mean null reference exception? I see that in your code your are looking for a "image_url" element but in your sample there is an "image" element.