0

我试图解析包含某个频道上所有上传视频的 XML 文件。我试图在其中一个<media:content>节点中获取 URL 属性的值并将其放在 ViewerLocation 字段中。但是有几个。我目前的代码是这样的:

var videos = from xElem in xml.Descendants(atomNS + "entry")
select new YouTubeVideo()
{
    Title = xElem.Element(atomNS + "title").Value,
    Description = xElem.Element(atomNS + "content").Value,
    DateUploaded = xElem.Element(atomNS + "published").Value,
    ThumbnailLocation = xElem.Element(mediaNS + "group").Element(mediaNS + "content").Attribute("url").Value,
    ViewerLocation = xElem.Element(mediaNS + "group").Element(mediaNS + "content").Attribute("url").Value
};

它为我提供了 XML 中的第一个节点,用于输入<media:content>您所期望的名称。但是,XML 中的第一个条目不是我想要的。我想要第二个。

下面是相关的 XML。

<!-- I currently get the value held in this node -->
<media:content 
  url='http://www.youtube.com/v/ZTUVgYoeN_b?f=gdata_standard...'
  type='application/x-shockwave-flash' medium='video'
  isDefault='true' expression='full' duration='215' yt:format='5'/>

<!-- What i actually want is this one -->
<media:content
  url='rtsp://rtsp2.youtube.com/ChoLENy73bIAEQ1kgGDA==/0/0/0/video.3gp'
  type='video/3gpp' medium='video'
  expression='full' duration='215' yt:format='1'/>

<media:content
  url='rtsp://rtsp2.youtube.com/ChoLENy73bIDRQ1kgGDA==/0/0/0/video.3gp'
  type='video/3gpp' medium='video'
  expression='full' duration='215' yt:format='6'/>

我想要第二个节点,因为它具有“video/3gpp”类型。我将如何选择那个?我的逻辑是

if attribute(type == "video/3gpp") 得到这个值。

但我不知道如何在 Linq 中表达这一点。

谢谢,

丹尼。

4

2 回答 2

0

可能是这样的;

where xElem.Element(atomNS + "content").Attribute("type").Value == "video/3gpp"

编辑:如果不假设 OP 不了解 Linq,我不太知道如何扩展和解释这一点。您想进行原始查询;

from xElem in xml.Descendants(atomNS + "entry") 
where xElem.Element(atomNS + "content").Attribute("type").Value == "video/3gpp"
select new YouTubeVideo() { 
  ...
}

您可以查询节点的属性,就像您可以查看文档的元素一样。如果有多个元素具有该属性,那么你可以(假设你总是想要你找到的第一个)..

  ( from xElem in xml.Descendants(atomNS + "entry") 
    where xElem.Element(atomNS + "content").Attribute("type").Value == "video/3gpp"
    select new YouTubeVideo() { 
      ...
    }).First();

我更改了原始帖子,因为我相信您要查询的节点是 Element(atomNS + "content"),而不是顶级 xElem

于 2012-07-11T12:11:42.920 回答
0

使用此Xml 库中的 XPath (只是因为我知道如何使用它)和相关的 Get 方法:

string videoType = "video/3gpp";

XElement root = XElement.Load(file); // or .Parse(xmlstring)
var videos = root.XPath("//entry")
    .Select(xElem => new YouTubeVideo()
    {
        Title = xElem.Get("title", "title"),
        Description = xElem.Get("content", "content"),
        DateUploaded = xElem.Get("published", "published"),
        ThumbnailLocation = xElem.XGetElement("group/content[@type={0}]/url", "url", videoType),
        ViewerLocation = xElem.XGetElement("group/content[@type={0}]/url", "url", videoType)
    });

如果视频类型没有改变,您可以将 XGetElement 替换为:

xElem.XGetElement("group/content[@type='video/3gpp']/url", "url")

不必使用该库指定名称空间就更干净了。有微软的XPathSelectElements()XPathSelectElement()您可以查看,但它们要求您指定名称空间并且没有很好的Get方法 imo。需要注意的是,该库不是一个完整的 XPath 实现,但它确实适用于上述内容。

于 2012-07-12T14:07:33.467 回答