How to get a list of children from an XDocument object?

I am trying to get all the elements of a "video" 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> 

Below, we select only the root of the node and all the children. I would like to get all the elements of the video in 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 length == 1. It contains the root element and all child elements.

+4
source share
1 answer

You want to select Descendants ("video"). "Video" is your root entry, of which 1 element. The internal elements of the video are what you want to request.

Example:

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

This gives you an IEnumerable of an anonymous type with two string properties. Otherwise, you can simply select the β€œvideo” and get an IEnumerable<XElement> , which you would further analyze as needed.

+9
source

Source: https://habr.com/ru/post/1305499/


All Articles