Created
October 13, 2011 18:26
-
-
Save nissuk/1285035 to your computer and use it in GitHub Desktop.
C#: XML属性値を取得する単純な例(Linq, XPath)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Xml.Linq; | |
using System.Xml.XPath; | |
using System.Xml; | |
namespace Example | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// LinqでURLを取得 | |
var xml = XDocument.Load("http://matome.naver.jp/feed/matome/2127198911354142701"); | |
var media = xml.Root.GetNamespaceOfPrefix("media"); | |
var query = xml.Descendants(media + "content").Select(x => x.Attribute("url").Value); | |
foreach (var url in query) | |
{ | |
Console.WriteLine(url); | |
} | |
// Linq + XPathでURLを取得 | |
var manager = new XmlNamespaceManager(new NameTable()); | |
manager.AddNamespace("media", media.ToString()); | |
var query2 = ((IEnumerable<object>)xml.XPathEvaluate("//media:content/@url", manager)) | |
.Select(x => ((XAttribute) x).Value); | |
foreach (var url in query2) | |
{ | |
Console.WriteLine(url); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment