Difference between revisions of "C#:Looping over DOM Tutorial"

From Progzoo
Jump to: navigation, search
(GetElementsByTagName)
(GetElementsByTagName)
Line 32: Line 32:
 
       XmlDocument doc = new XmlDocument();
 
       XmlDocument doc = new XmlDocument();
 
       doc.Load("world.xml");
 
       doc.Load("world.xml");
       XmlNodeList nl = doc.GetElementsByTagName("region");
+
       XmlNodeList nl = doc.GetElementsByTagName("country");
 
       Console.WriteLine(nl.Item(0));
 
       Console.WriteLine(nl.Item(0));
 +
    }catch (Exception e){
 +
      Console.WriteLine(e.ToString());
 +
    }
 +
  }
 +
}
 +
</prog>
 +
<answer>
 +
using System;
 +
using System.Xml;
 +
class Demo{
 +
  public static void Main(string[] args){
 +
    try{
 +
      XmlDocument doc = new XmlDocument();
 +
      doc.Load("world.xml");
 +
      XmlNodeList nl = doc.GetElementsByTagName("country");
 +
      Console.WriteLine(nl.Count);
 +
    }catch (Exception e){
 +
      Console.WriteLine(e.ToString());
 +
    }
 +
  }
 +
}
 +
 +
</answer>
 +
</question>
 +
==Searching for large countries==
 +
<question lang='cs' className='Demo' copyFile='world.xml'>
 +
The program shown uses GetElementsByTagName. It returns a NodeList.
 +
The class NodeList includes the '''Count''' property.
 +
<p class='imper'>Change the program so that it prints the number of the country elements.
 +
</p>
 +
<prog>
 +
using System;
 +
using System.Xml;
 +
class Demo{
 +
  public static void Main(string[] args){
 +
    try{
 +
      XmlDocument doc = new XmlDocument();
 +
      doc.Load("world.xml");
 +
      XmlNodeList nl = doc.GetElementsByTagName("country");
 +
      for (int i=0;i<nl.Count;i++){
 +
        XmlElement e = (XmlELement) nl[i];
 +
        if (e.GetAttribute("pop").Length>8)
 +
          Console.WriteLine(e.GetAttribute("name"));
 +
      }
 
     }catch (Exception e){
 
     }catch (Exception e){
 
       Console.WriteLine(e.ToString());
 
       Console.WriteLine(e.ToString());

Revision as of 22:50, 12 July 2008

The file http://progzoo.net/world.xml is as shown:
<world>
 <region name='Europe'>
  <country id='de' name='Germany' pop='82000000'/>
  <country id='fr' name='France'  pop='60000000'/>
  ...
 </region>
 <region id='Asia'>
  <country id='cn' name='China' pop='1300000000'/>
   ...
 </region>
 ...
</world>

This this tutorial we look at the following members of the DOM interface

NodeList

GetElementsByTagName

The program shown uses GetElementsByTagName. It returns a NodeList. The class NodeList includes the Count property.

Change the program so that it prints the number of the country elements.


[Font] [Default] [Show] [Resize] [History] [Profile]

Searching for large countries

Line: 123 DOMDocument::loadXML(): error parsing attribute name in Entity, line: 15
Line: 123 DOMDocument::loadXML(): attributes construct error in Entity, line: 15
Line: 123 DOMDocument::loadXML(): Couldn't find end of Start Tag nl.Count line 15 in Entity, line: 15