如何从XDocument对象获取子元素列表? [英] How do I get a list of child elements from XDocument object?

查看:482
本文介绍了如何从XDocument对象获取子元素列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从如下所示的XML文件中获取所有视频"元素及其属性:

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>

以下内容将仅选择根节点和所有子节点.我想将所有视频"元素放入IEnumerable.有人可以告诉我我在做什么错吗?

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;

上面的方法返回一个长度== 1的集合.它包含根元素和所有子元素.

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

推荐答案

您要选择Descendants("video"). 视频"似乎是您的根条目,其中有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.

示例:

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

这为您提供了一个具有两个字符串属性的匿名类型的IEnumerable.否则,您只需选择视频"并获得一个IEnumerable<XElement>,您可以根据需要对其进行进一步解析.

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.

这篇关于如何从XDocument对象获取子元素列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆