Reputation: 1024
I can get the header attributes from the XML but want to extract the title, which is a few nodes down. I've left my latest attempt in the code. FirstAttributes work so I know I am connecting and if I return Console.WriteLine(e) I get the full XML.
var url = "http://musicbrainz.org/ws/2/release-group/?query=artist:%22coldplay%22%20AND%20primarytype:%22single%22";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Hello World Super Script";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
XDocument doc = XDocument.Load(response.GetResponseStream());
IEnumerable<XElement> childList =
from el in doc.Elements()
select el;
//title is element we need
foreach (XElement e in childList)
Console.WriteLine("{0} {1} {2}", e.FirstAttribute, e.FirstAttribute.NextAttribute, e.Element("release-group").Attribute("title"));
Researched: C# extracting data from XML
Upvotes: 0
Views: 352
Reputation: 34421
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
const string URL = @"http://musicbrainz.org/ws/2/release-group/?query=artist:%22coldplay%22%20AND%20primarytype:%22single%22";
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.UserAgent = "Hello World Super Script";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
XDocument doc = XDocument.Load(response.GetResponseStream());
XNamespace ns = doc.Root.GetDefaultNamespace();
List<Group> groups = doc.Descendants(ns + "release-group").Select(x => new Group()
{
title = (string)x.Element(ns + "title"),
name = (string)x.Descendants(ns + "name").FirstOrDefault(),
releaseTitles = x.Element(ns + "release-list").Descendants(ns + "title").Select(y => (string)y).ToArray()
}).ToList();
}
}
public class Group
{
public string title { get; set; }
public string name { get; set; }
public string[] releaseTitles { get; set; }
}
}
Upvotes: 1
Reputation: 18155
You could do the following.
var doc = XDocument.Load(response.GetResponseStream());
XNamespace ns = "http://musicbrainz.org/ns/mmd-2.0#";
var titleList = doc.Descendants(ns + "title");
foreach (var element in titleList)
Console.WriteLine(element.Value);
The XDocument.Descendants()
allows you to search for the child node with specified name. Do note that you need to specify the namespace along with element name.
If you observe the response from the WebRequest, you can find the details of namespace.
xmlns="http://musicbrainz.org/ns/mmd-2.0#"
Upvotes: 1