我需要提取此XML文档的XML节点:
http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad
我无法弄清楚这一点。下面是我用来从该URL读取XML的当前代码。
private void button1_Click(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad"));
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
this.textBox1.Text = xdoc.LastNode.ToString();
}
}
如何从提供的URL中访问XML文档中的节点lyric
?
答案 0 :(得分:4)
对于这种情况,请使用Linq To Xml。
请注意,xml结果中有一个名称空间(xmlns="http://api.chartlyrics.com/"
)。
一个非常基本的例子可能是:
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
var lyric = xdoc.Descendants(XName.Get("Lyric","http://api.chartlyrics.com/")).FirstOrDefault();
this.textBox1.Text = lyric.Value;
}
}