2011-12-25 113 views
1

我需要使用XmlTextReader循环浏览XML文档的节点。不幸的是,使用除XmlTextReader之外的其他任何东西都不是一种选择。XmlTextReader - 如何遍历节点

我的代码:

 
    class Program 
    { 
    private static void Main(string[] args) 
    { 
    XmlTextReader reader = new XmlTextReader("http://api.own3d.tv/liveCheck.php?live_id=180491"); 
      while (reader.Read()) 
      { 
       switch (reader.NodeType) 
       { 
        case XmlNodeType.Text: 
         Console.WriteLine("Live: " + reader.Value); 
         break; 
       } 
      } 
      Console.ReadLine(); 
     } 
    }

XML used:

<own3dReply> 
<liveEvent> 
    <isLive>true</isLive> 
    <liveViewers>225</liveViewers> 
    <liveDuration>1222</liveDuration> 
</liveEvent> 
</own3dReply> 

What it's outputting to console:

 

    Live: true 
    Live: 225 
    Live: 1222 

What it needs to output:

 

    Live: true 
    Viewers: 225 
    Duration: 1222 

It needs to iterate through each node and do this, and I just can't figure it out. I tried using switch and while statements, but I just can't seem to get it to work.

+1

出于兴趣,*为什么*是除XmlReader之外的任何其他选项?在给出限制时,提供原因总是有用的,因为它们会影响答案。 –

+1

另外,不要使用'new XmlTextReader()'。使用'XmlReader.Create()'。 –

+0

我想这是很好的处置它,所以使用使用:使用(var xtr = XmlReader.Create(uri)) –

回答

3

Instead of:

Console.WriteLine("Live: " + reader.Value); 

Use:

Console.WriteLine(string.Format("{0}: {1}", reader.LocalName, reader.Value)); 

The LocalName属性为您提供了节点(isLiveliveViewersliveDuration)的本地名称。如果需要,你可以对这些进行更多的字符串处理。

+0

'isLive' :)))) –

+0

@ L.B - 是啊...答案更新。 – Oded