如何从 XDocument 对象获取子元素列表?
我试图从如下所示的 XML 文件中获取所有“视频”元素及其属性:
<?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 中。有人可以告诉我我做错了什么吗?
IEnumerable<XElement> elements = from xml in _xdoc.Descendants("videos")
select xml;
上面返回一个长度== 1的集合。它包含根元素和所有子元素。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要选择后代(“视频”)。 “videos”似乎是您的根条目,其中有 1 个元素。视频的内部元素就是你想要查询的内容。
示例:
这为您提供了一个具有两个字符串属性的匿名类型的 IEnumerable。否则,您可以简单地选择“video”并获取
IEnumerable
,您可以根据需要进一步解析它。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:
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.