How do I get a list of child elements from XDocument object?

此生再无相见时 提交于 2019-12-19 09:18:24

问题


I am trying to get all of the "video" elements and their attributes from an XML file that looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<videos>
  <video title="video1" path="videos\video1.wma"/>
  <video title="video2" path="videos\video2.wma"/>
  <video title="video3" path="videos\video3.wma"/>
</videos>

The following will only select the root node and all of the children. I would like to get all of the 'video' elements into the IEnumerable. Can someone tell me what I'm doing wrong?

 IEnumerable<XElement> elements = from xml in _xdoc.Descendants("videos")
                           select xml;

The above returns a collection with a length == 1. It contains the root element and all the children.


回答1:


You want to select Descendants("video"). "videos" appears to be your root entry, of which there is 1 element. The inner elements of videos are what you want to query.

Example:

var query = from video in document.Descendants("video")
            select new
            {
                Title = video.Attribute("title").Value,
                Path = video.Attribute("path").Value
            };

That gives you an IEnumerable of an anonymous type with two string properties. Otherwise, you could simply select "video" and get an IEnumerable<XElement>, which you would further parse as needed.



来源:https://stackoverflow.com/questions/2542184/how-do-i-get-a-list-of-child-elements-from-xdocument-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!