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

From Progzoo
Jump to: navigation, search
(ParentNode and Name)
Line 60: Line 60:
 
</question>
 
</question>
  
==ParentNode and Name==
+
 
<question lang='cs' className='Demo' copyFile='world.xml'>
+
The "Name" property gives the tag name of an Element.
+
<p class='imper'>Change the program so that it prints the '''Name''' of the Element with
+
id "ca" and the '''Name''' of the '''ParentNode''' of that element.
+
</p>
+
<prog>
+
using System;
+
using System.Xml;
+
class Demo{
+
  public static void Main(string[] args){
+
    try{
+
      XmlDocument doc = new XmlDocument();
+
      doc.Load("world.xml");
+
      XmlElement e = doc.GetElementById("uk");
+
      Console.WriteLine(e.Name);
+
    }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");
+
      XmlElement e = doc.GetElementById("za");
+
      Console.WriteLine(e.Name);
+
      Console.WriteLine(e.ParentNode.Name);
+
    }catch (Exception e){
+
      Console.WriteLine(e.ToString());
+
    }
+
  }
+
}
+
</answer>
+
</question>
+
  
 
==Casting==
 
==Casting==

Revision as of 10:46, 14 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

DocumentElement
FirstChild
NextSibling

GetElementById

The program shown uses GetElementById.

Change the program so that it prints the name of the country with id "ca".


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


Casting

Often the DOM model returns an XmlNode when you are expecting an XmlElement. When this happens you must explicitly cast.

In this example the value p must be cast as an XmlElement

XmlNode p = e.ParentNode;

must be replaced by:

XmlElement p = (XmlElement) e.ParentNode;

Change the program so that it prints the name attribute of the parent Element with id "ca".


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