从Web服务读取XML节点

时间:2011-12-10 13:13:24

标签: c# xml web-services linq-to-xml xmlreader

我一直在使用一个简单的Windows Phone 7应用程序,使用带有XML响应的http上的Web服务。 我正在使用以下API http://api.chartlyrics.com/apiv1.asmx/

我的问题在于阅读返回的XML。

SearchLyricDirect函数,例如http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad返回以下xml:

   <GetLyricResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://api.chartlyrics.com/">
          <TrackId>0</TrackId>
          <LyricChecksum>8a84ddec06f4fffe067edd2fdbece21b</LyricChecksum>
          <LyricId>1710</LyricId>
          <LyricSong>Bad</LyricSong>
          <LyricArtist>Michael Jackson</LyricArtist>
          <LyricUrl>
                 http://www.chartlyrics.com/28h-8gWvNk-Rbj1X-R7PXg/Bad.aspx
          </LyricUrl>
          <LyricCovertArtUrl>
                 http://ec1.images-amazon.com/images/P/B000CNET66.02.MZZZZZZZ.jpg
          </LyricCovertArtUrl>
          <LyricRank>9</LyricRank>
          <LyricCorrectUrl>
                 http://www.chartlyrics.com/app/correct.aspx?lid=MQA3ADEAMAA=
          </LyricCorrectUrl>
          <Lyric>
                    .......Lyric.......
          </Lyric>
   </GetLyricResult>

我尝试过使用XmlReader,但它说有非法字符,例如XmlReader xmlr = XmlReader.Create(e.Result);

我尝试使用XDocument,但我无法获取“GetLyricResult”下的元素的任何值。

  XDocument xmltest = XDocument.Parse(e.Result);
  Console.WriteLine(xmltest.Element("Lyric").Value);

我确信这很简单。

谢谢!

2 个答案:

答案 0 :(得分:3)

您没有关注已定义的 XML命名空间

<GetLyricResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
                xmlns="http://api.chartlyrics.com/">

您需要做的是在Linq-to-XML查询中定义XML命名空间:

 XDocument xmltest = XDocument.Parse(e.Result);
 XNamespace ns = "http://api.chartlyrics.com/";

 Console.WriteLine(xmltest.Element(ns + "GetLyricResult").Element(ns + "Lyric").Value);

另外:你的代码无论如何都不会起作用 - 如果你使用.Element,你需要引用root中的所有元素 - 所以在这里你首先需要“解析”<GetLyricResult> root节点,只有在此之后,您才能进入并抓住<Lyric>节点

答案 1 :(得分:0)

使用xmlNodeList:

XmlNodeList trackId= xmlDocument.SelectNodes("/GetLyricResult/TrackId");

然后写内容:

for (int i = 0; i < trackId.Count; i++)
                {
                    Console.WriteLine("{0}",
                            trackId[i].InnerText);
                }